MPesaGateway-MCP
A Model Context Protocol adapter engineered for seamless incorporation with Safaricom's Daraja platform, facilitating execution of core financial operations such as disbursements, status verification, and data retrieval concerning M-Pesa services. Primarily oriented towards educational endeavors and proof-of-concept deployments within sandbox environments.
Author

jameskanyiri
Quick Info
Actions
Tags
M-Pesa Connector Protocol Interface
🛑 Critical Repository Relocation Alert
This functional unit's source code base has migrated. For the most current version or to submit modifications, navigate to:
This implementation of the Model Context Protocol (MCP) server acts as a bridge, allowing intelligent agents to interface directly with Safaricom's Daraja financial gateway, thus enabling fluid command execution over M-Pesa functionalities.
🛑 Caution: Not Suitable for Live Operations
This software remains in an active development phase and is explicitly discouraged for deployment in production settings. Its intended uses are:
- Knowledge acquisition and exploratory scripting
- Controlled development and qualification phases
- Initial validation of concepts
Prior to moving to a live production schema, mandatory steps include:
- Comprehensive security auditing and penetration testing
- Robust implementation of all foreseeable error scenarios
- Full feature parity with initial design specifications
- Adherence to all operational prerequisites stipulated by Safaricom
Grasping the MCP Server Paradigm
MCP (Model Context Protocol) servers empower Large Language Models (LLMs) by granting them controlled access to external operational capabilities. An MCP infrastructure supports three primary classes of functionality:
- Data Assets (Resources): Data representations accessible via read operations (e.g., server responses).
- Invocation Mechanisms (Tools): Discrete functions executable by the LLM (contingent upon user consent).
- Instruction Blueprints (Prompts): Pre-defined textual templates designed to guide users toward task completion.
Specifically, the Daraja MCP utilizes this structure to couple advanced AI constructs with the M-Pesa API provided by Safaricom.
High-Level Synopsis
Daraja MCP establishes a vital intermediary layer connecting artificial intelligence, financial technology, and the M-Pesa ecosystem, democratizing access to automated financial routines. By standardizing the communication channel between LLMs and transactional processing, this connector empowers AI-driven applications to manage outgoing payments, retrieve historical transaction metadata, and automate reconciliation procedures with minimal friction.
Principal Capabilities
- ✅ AI-Orchestrated M-Pesa Transfers – Facilitates LLMs in executing B2C, C2B, and B2B fund movements.
- ✅ Uniform Interoperability – MCP mandates compatibility across diverse AI toolkit architectures.
- ✅ Resilient & Secure – Incorporates OAuth 2.0 for authorization and supports high-volume transactional throughput.
- ✅ Adaptable Automation – Allows AI entities to poll current account standings, generate formal billing instruments, and automate ledger matching.
Prerequisites
- Runtime environment: Python version 3.12 or newer
- Valid Safaricom Daraja API Secret Key and Consumer Identifier
Installation Protocol
Phase 1: Setting Up the Execution Environment
- Acquire the 'uv' Package Manager
For Unix-like systems (macOS/Linux):
bash curl -LsSf https://astral.sh/uv/install.sh | sh
For Windows (using PowerShell):
powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
- Clone the Project Repository
bash git clone https://github.com/jameskanyiri/DarajaMCP.git cd DarajaMCP
- Establish and Activate a Virtual Context
bash uv venv source .venv/bin/activate # Windows users: .venv\Scripts\activate
✅ Expected Feedback: The command line prompt visualization will change, confirming the isolated environment is active.
- Load Required Libraries bash uv sync
Phase 2: Configuring Environmental Variables
- Duplicate the template configuration file:
bash cp .env.example .env
- Modify the newly created
.envfile to incorporate your specific API keys and operational settings.
Reminder: For development iterations, utilize the sandbox endpoint URLs. Transition to the production URLs only upon achieving full operational readiness.
Operational Guide
Integration Testing with Claude Desktop Client
-
Install the Claude Desktop Application
-
Secure the most current iteration from Claude Desktop
-
Ensure the application is running its newest available build
-
Configure the Desktop Client Settings
-
Locate and open the Claude Desktop configuration file:
bash # MacOS/Linux Systems code ~/Library/Application\ Support/Claude/claude_desktop_config.json
# Windows Systems code %APPDATA%\Claude\claude_desktop_config.json
-
Create this JSON file if it does not yet exist.
-
Inject Server Configuration Data Choose one of the following JSON structures to define the server connection:
#### Anthropic's Preferred Schema
{ "mcpServers": { "daraja": { "command": "uv", "args": [ "--directory", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/DarajaMCP", "run", "main.py" ] } } }
#### Verified Operational Configuration
{ "mcpServers": { "DarajaMCP": { "command": "/ABSOLUTE/PATH/TO/PARENT/.local/bin/uv", "args": [ "--directory", "/ABSOLUTE/PATH/TO/PARENT/FOLDER/DarajaMCP", "run", "main.py" ] } } }
Important Note:
- Substitute
/ABSOLUTE/PATH/TO/PARENTwith the actual directory path.- To dynamically ascertain the fully qualified path for
uv, execute the following command:
bash # MacOS/Linux Systems which uv
# Windows Systems where uv
- Validate Connectivity
- Save the configuration document.
- Restart the Claude Desktop application.
- Inspect the user interface for the wrench icon 🔨.
- Clicking it will display the available functionalities:
- generate_access_token
- stk_push (Scheduled for future release)
- query_transaction_status (Scheduled for future release)
- b2c_payment (Scheduled for future release)
- account_balance (Scheduled for future release)
Defined Tools and Instructional Scripts
Payment Execution Mechanisms
stk_push
Initiates an M-Pesa Subscriber Initiated (STK) push operation, prompting the recipient to approve a transaction on their mobile handset.
Input Parameters:
amount(integer): The monetary value targeted for the transferphone_number(integer): The mobile number designated for the transaction
Output: M-PESA API response serialized as JSON format.
generate_qr_code
Constructs a scannable QR code image associated with a payment instruction.
Input Parameters:
merchant_name(string): Official designation of the vendor/M-Pesa Merchant Identitytransaction_reference_no(string): Unique identifier for this specific transactionamount(integer): The gross sum involved in the remittancetransaction_type(Literal["BG", "WA", "PB", "SM", "SB"]): The classification of the transaction typecredit_party_identifier(string): The receiving entity identifier (Till number, Paybill, Phone, or Merchant Buy Goods ID)
Output: A JSON object containing the generated QR code data structure.
Payment Instruction Prompts
stk_push_prompt
Generates a structured text instruction designed to trigger an M-Pesa STK push payment request via an agent.
Input Parameters:
phone_number(string): The subscriber's mobile contact numberamount(integer): The quantity of funds to transferpurpose(string): A brief explanation defining the payment context
Output: A precisely formatted text string suitable for STK push command invocation.
generate_qr_code_prompt
Creates a textual directive for commissioning an M-Pesa QR code payment request.
Input Parameters:
merchant_name(string): The vendor's registered business titleamount(integer): The financial sum requiredtransaction_type(string): Type identifier (e.g., BG for Buy Goods, PB for Paybill)identifier(string): The target recipient's identification code (e.g., till, phone, paybill)reference(string, optional): The specific transaction tracking number. A default will be substituted if omitted.
Output: A formatted instructional string for QR code generation.
Document Management Mechanisms
create_source
Establishes a connectivity link from an initial data reservoir to the unstructured processing server.
Input Parameters:
connector_name(string): The desired identifier for the input source link
Output: Details of the newly provisioned source link, including its name and system ID.
create_destination
Establishes a connectivity link from the unstructured server to the final data persistence location.
Input Parameters:
connector_name(string): The desired identifier for the output storage link
Output: Details of the newly provisioned destination link, including its name and system ID.
create_workflow
Orchestrates a sequence of steps to flow data from the defined source to the specified destination location.
Input Parameters:
workflow_name(string): A unique appellation for the automated processsource_id(string): The unique identifier of the input data connectordestination_id(string): The unique identifier of the output data connector
Output: Comprehensive metadata for the created workflow, including its name, ID, operational state, type, linked sources/sinks, and scheduling parameters.
run_workflow
Immediately triggers the execution sequence of a defined workflow.
Input Parameters:
workflow_id(string): The unique system identifier for the target workflow
Output: The reported status code following the workflow's execution attempt.
get_workflow_details
Retrieves granular configuration and status information pertaining to a specific workflow instance.
Input Parameters:
workflow_id(string): The unique system identifier for the target workflow
Output: A detailed object describing the workflow's structure and current status.
fetch_documents
Retrieves the corpus of documentation that underwent analysis during recent workflow execution cycles.
Input Parameters: None
Output: A catalogued collection of analyzed documentation artifacts.
Instructional Scripts
create_and_run_workflow_prompt
Generates a comprehensive instruction set for programmatically establishing and initiating a document processing pipeline.
Input Parameters:
user_input(string): The natural language description of the required processing task
Output: A polished, structured prompt text suitable for LLM interpretation, detailing the necessary connector setup and workflow launch.
Demonstration:
python
Illustrative invocation
prompt = await create_and_run_workflow_prompt( user_input="Process all PDF invoices from the invoices folder and store them in the processed folder" )
Result: "The user wants to achieve Process all PDF invoices from the invoices folder and store them in the processed folder. Assist them by creating a source connector and a destination connector, then setting up the workflow and executing it."
Data Assets
Currently, no external data assets are exposed via this interface.
Licensing Information
MIT License
Appreciation Notes
- Gratitude extended to Safaricom for providing access to the Daraja API services.
- Acknowledgement to Anthropic for conceptualizing and furnishing the MCP architectural blueprint.
- Recognition for all community members who contributed to this software project.
Communication Channel
For any inquiries or issues, please submit a formal report via the project's GitHub issue tracker.
WIKIPEDIA: XMLHttpRequest (XHR) represents an Application Programming Interface realized as a JavaScript object. Its methods are responsible for transmitting Hypertext Transfer Protocol (HTTP) requests originating from a web browser destined for a remote web server. These methods permit web-based applications to asynchronously dispatch inquiries to the server post-page rendering and receive corresponding data back. XMLHttpRequest forms a core element of the Ajax development methodology. Prior to the mainstream adoption of Ajax, standard page navigation relied predominantly on hyperlink activations and form submissions, often resulting in the complete replacement of the viewing document.
== Chronology == The conceptual foundation for XMLHttpRequest was first articulated in the year 2000 by the engineering team behind Microsoft Outlook development. This concept was subsequently integrated into the Internet Explorer 5 browser (released in 1999). However, the initial coding structure did not employ the specific identifier XMLHttpRequest. Instead, developers leveraged instantiation via ActiveXObject("Msxml2.XMLHTTP") and ActiveXObject("Microsoft.XMLHTTP"). By the release of Internet Explorer 7 (2006), universal browser support for the XMLHttpRequest identifier was established. The XMLHttpRequest identifier has since evolved into the accepted convention across all primary browser engines, including Mozilla’s Gecko rendering engine (since 2002), Safari version 1.2 (2004), and Opera version 8.0 (2005).
=== Formal Specifications === The World Wide Web Consortium (W3C) formally released a Working Draft specification detailing the XMLHttpRequest object on April 5, 2006. On February 25, 2008, the W3C issued the Level 2 specification draft. This Level 2 iteration introduced capabilities for monitoring request progress, enabling cross-origin data retrieval, and managing raw byte streams. By the conclusion of 2011, the Level 2 specification content was merged back into the primary, original standard document. As of the end of 2012, development oversight transitioned to the WHATWG group, which now maintains a continuous documentation stream utilizing Web IDL definitions.
== Operational Use == Generally, the procedure for dispatching a data request using XMLHttpRequest necessitates several discrete programming steps.
- Instantiate an XMLHttpRequest object via a constructor call:
- Invoke the "open" method to define the request methodology (GET/POST), specify the target resource endpoint, and select between blocking (synchronous) or non-blocking (asynchronous) execution:
- If utilizing asynchronous execution, attach an event handler function designed to be invoked upon changes in the request's status:
- Initiate the transmission sequence by calling the "send" method, potentially including outgoing payload data:
- Process status changes within the designated event listener. If the server transmits response content, this data is typically aggregated in the "responseText" attribute by default. When the object finalizes processing the reply, its status code advances to state 4, signifying the "done" condition. Beyond these foundational steps, XMLHttpRequest furnishes extensive options to fine-tune the transmission parameters and response interpretation methods. Custom header fields can be appended to the request to instruct the server on expected fulfillment protocols, and data can be uploaded concurrently with the "send" call. The resulting response stream can be parsed directly from JSON format into native JavaScript data structures, or processed incrementally as data chunks arrive rather than awaiting the complete payload. Furthermore, the operation can be terminated prematurely or configured to time out if completion is not achieved within a specified duration.
== Inter-Domain Communication ==
In the initial phases of the World Wide Web's evolution, developers recognized the possibility of circumventing security restrictions that pre
