What Is the Model Context Protocol (MCP)

The Model Context Protocol (MCP) is an open standard developed by Anthropic to enable easy and standardized integration between AI models and external tools. It acts as a universal connector, allowing large language models (LLMs) to interact dynamically with APIs, databases, and business applications.

Originally built to improve Claude's ability to interact with external systems, Anthropic decided to open-source MCP in early 2024 to encourage industry-wide adoption. By making MCP publicly available, they aimed to create a standardized framework for AI-to-tool communication, reducing reliance on proprietary integrations and enabling greater modularity and interoperability across AI applications.

MCP follows a client-server architecture where:

  • MCP clients (e.g., Claude Desktop) request information and execute tasks.
  • MCP servers provide access to external tools and data sources.
  • Host applications use MCP to communicate between models and tools.

Extending Daraja MCP Beyond payments

While the M-Pesa Daraja API is primarily known for handling mobile payments, its capabilities can be extended to support a wider range of financial and business operations using MCP. Instead of just processing payments, businesses can integrate document processing, invoicing, and financial automation into their workflows.

From Payments to Full Invoice Processing

Imagine receiving an invoice from a supplier. Instead of manually entering details and initiating payment, an AI-powered Daraja MCP server can:

  1. Extract invoice details using Unstructured.io
  2. Store the extracted data in a database like MongoDB for tracking and reconciliation.
  3. Validate the invoice against purchase orders to ensure authenticity.
  4. Trigger an M-Pesa payment automatically via Daraja API once verified.
  5. Log the payment confirmation and update financial records.

How It Works

  • File Upload: The invoice is uploaded to an S3 bucket.
  • Document Processing: An MCP-powered service extracts and structures key details.
  • Database Storage: The data is stored in MongoDB for future reference.
  • Automated Payment: A payment request is initiated via Daraja based on the extracted details.

This end-to-end automation simplifies business operations, eliminates manual errors, and ensures timely payments.

Getting started with the Daraja MCP Server

In this tutorial, I'll walk you through how to set up and use the Daraja MCP server to:

Upload invoices to AWS S3

Extract invoice details using Unstructured.io

Store extracted data in MongoDB

Automate payments via M-Pesa Daraja API

Before You Begin

Ensure you have Python 3.10+ installed.

Step 1: Setting Up Your Environment

1. Install uv Package Manager

We use uv for managing dependencies efficiently.

For Mac/Linux, run:

Bash
curl -LsSf https://astral.sh/uv/install.sh | sh

For Windows (PowerShell), run:

Powershell
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

2. Clone the Repository

First, clone the project from GitHub:

Bash
git clone https://github.com/jameskanyiri/DarajaMCP.git cd DarajaMCP

3. Create and Activate a Virtual Environment

Bash
uv venv source .venv/bin/activate # On Windows: .venv\Scripts\activate

Expected Output: Your terminal prompt should change, indicating the virtual environment is activated.

4. Install Dependencies

Bash
uv sync

Step 2: Setting Up Environment Variables

Next, we create a .env file that contains all the keys and tokens required for this project.

Jsx
UNSTRUCTURED_API_KEY="your_unstructured_api_key" AWS_ACCESS_KEY_ID="your_aws_key" AWS_SECRET_ACCESS_KEY="your_aws_secret" AWS_S3_ENDPOINT="your_s3_endpoint" S3_REMOTE_URL="your_s3_bucket_url" MONGODB_URI="your_mongodb_uri" DATABASE_NAME="daraja_mcp_db" COLLECTION_NAME="invoices" MPESA_CONSUMER_KEY="your_mpesa_consumer_key" MPESA_CONSUMER_SECRET="your_mpesa_consumer_secret" PASSKEY="your_mpesa_passkey" BUSINESS_SHORTCODE="your_business_shortcode" CALLBACK_URL="your_callback_url" BASE_URL="https://sandbox.safaricom.co.ke"

Step 3: Generating Required Keys and Tokens

1. Generating Daraja API Tokens

To generate M-Pesa Daraja API tokens for authentication:

  1. Visit Safaricom Daraja API and sign up/log in.
  2. Navigate to MY APPSCreate New App.
  3. Provide an app name and select the API products you need
  4. Click Create App.
  5. Once created, copy the Consumer Key and Consumer Secret—you'll use these for API authentication.

Expected Output: Your app dashboard will display the Consumer Key & Consumer Secret.


2. Setting Up AWS for Invoice Storage

To store invoices in AWS S3 and enable secure access:

Step 1: Create an AWS Account

  • Sign up at AWS if you don't already have an account.
  • Complete the onboarding process.

Step 2: Create an S3 Bucket

  1. Go to the S3 ConsoleAWS S3.
  2. Click "Create Bucket".
  3. Configure:
    • Bucket name: e.g., daraja-invoices.
    • Block public access: Make sure it is disabled
  4. Click Create Bucket.

Expected Output: Your S3 bucket is now ready for invoice storage.

Step 3: Create an IAM User for S3 Access

  1. Go to the IAM ConsoleAWS IAM.
  2. Click UsersCreate New User.
  3. Enter a User Name: e.g., daraja-mcp-user.
  4. Client Next
  5. To set user permissions click Attach existing policies directly.
  6. Search for AmazonS3FullAccess → Click Next
  7. Create user

Step 4: Generate Access Key and Secret

  1. Go to the IAM ConsoleAWS IAM.
  2. Click UsersClick on your user eg daraja-mcp-user.
  3. Click Security credentials → Create access Key.
  4. Select Others → Click Next
  5. Set description then click Create Access Key
  6. Copy the AWS Access Key ID and Secret Access Key—store them securely.

Expected Output: You now have an IAM user with S3 access credentials.


3. Setting Up MongoDB Atlas for Invoice Storage

To store extracted invoice data, use MongoDB Atlas:

Step 1: Create a MongoDB Atlas Account

Step 2: Create a Database Cluster

  1. Click "Create a New Cluster" (Choose Free Tier for testing).
  2. Select a Cloud Provider and Region.
  3. Click Create Cluster and wait for the setup to complete.

Step 3: Create a Database User

  1. Navigate to Database AccessCreate New Database User.
  2. Set a username and password for secure access.
  3. Database user privileges. add buil-in roles select Atlas Admin

Step 4: Get Your MongoDB Connection String

  1. Go to Database ClustersConnectDrivers.

  2. Copy the MongoDB Connection String (it should look like this):

    mongodb+srv://<username>:<password>@cluster0.mongodb.net/<database>?retryWrites=true&w=majority
  3. Replace <username> and <password> with your credentials.

Expected Output: Your MongoDB cluster is live, and you have a connection string.

4. Updating the .env File with Credentials

After generating all the required credentials, update your .env file:

Now your system is fully configured to:

  • Authenticate Daraja API requests
  • Store invoices in AWS S3
  • Process and save extracted data in MongoDB

Updated Invoice Processing & Payment Workflow

  1. Upload Invoice to AWS S3
    • The invoice file is uploaded to an AWS S3 bucket for storage and later processing.

Invoice processing flow

  1. Create a Source Connector

    • A source connector is initialized to retrieve the invoice data from AWS S3.

    Source connector

  2. Create a Destination Connector

    • A destination connector is set up to store processed invoice data.

    Destination connector

  3. Set Up the Workflow

    • The workflow invoice_processing_workflow is created, linking the source (AWS) and destination connectors.

    Invoice processing workflow

  4. Run the Workflow

    • The system executes the workflow, extracting and processing the invoice data.

    Run the workflow

    Workflow run details

  5. Retrieve Processed Invoice Details

    • Extracted invoice details include:
      • Invoice Number: INV-2025-001
      • Billed To: Client Company, Nairobi, Kenya
      • Services Provided: AI consultation, M-Pesa API integration
      • Total Amount: 63,800 KES

    Chat: invoice processing (1)

    Chat: invoice processing (2)

    Chat: invoice processing (3)

    Chat: invoice processing (4)

    Chat: invoice processing (5)

  6. Initiate Payment via M-Pesa

    • A partial payment of 300 KES is initiated via stk_push.
    • Response Code: 0 (Success)
    • Customer Message: "Request accepted for processing."

    Initiate payment via M-Pesa