Skip to main content
Glama

M-Pesa STK Push

mpesa_stk_push
Destructive

Send an M-Pesa STK Push payment prompt to a customer's phone. The customer enters their M-Pesa PIN to authorize payment. Returns a CheckoutRequestID for tracking with mpesa_stk_query.

Instructions

Trigger an M-Pesa STK Push — sends a payment prompt to the customer's phone. The customer enters their M-Pesa PIN to complete payment. Returns a CheckoutRequestID to track the transaction with mpesa_stk_query. Async: use mpesa_stk_query after 10-30 seconds to check completion.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
phoneYesCustomer phone number (any Kenyan format: +254..., 07..., 254...)
amountYesAmount in KES (whole number, minimum 1)
account_refYesAccount reference shown to customer on their phone (max 12 chars)
descriptionNoTransaction description (max 13 chars)Payment

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The actual handler function for the 'mpesa_stk_push' tool. Triggers an M-Pesa STK Push payment prompt on the customer's phone, calls the Safaricom Daraja API, and returns a response with CheckoutRequestID.
    def mpesa_stk_push(
        phone: Annotated[str, "Customer phone number (any Kenyan format: +254..., 07..., 254...)"],
        amount: Annotated[int, "Amount in KES (whole number, minimum 1)"],
        account_ref: Annotated[str, "Account reference shown to customer on their phone (max 12 chars)"],
        description: Annotated[str, "Transaction description (max 13 chars)"] = "Payment",
    ) -> dict:
        """
        Trigger an M-Pesa STK Push — sends a payment prompt to the customer's phone.
        The customer enters their M-Pesa PIN to complete payment.
        Returns a CheckoutRequestID to track the transaction with mpesa_stk_query.
        Async: use mpesa_stk_query after 10-30 seconds to check completion.
        """
        shortcode = os.environ["MPESA_SHORTCODE"]
        passkey   = os.environ["MPESA_PASSKEY"]
        callback  = os.environ["MPESA_CALLBACK_URL"]
        timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        password  = base64.b64encode(f"{shortcode}{passkey}{timestamp}".encode()).decode()
        phone     = _normalize_phone(phone)
    
        payload = {
            "BusinessShortCode": shortcode,
            "Password":          password,
            "Timestamp":         timestamp,
            "TransactionType":   "CustomerPayBillOnline",
            "Amount":            amount,
            "PartyA":            phone,
            "PartyB":            shortcode,
            "PhoneNumber":       phone,
            "CallBackURL":       callback,
            "AccountReference":  account_ref[:12],
            "TransactionDesc":   description[:13],
        }
    
        token = _get_mpesa_token()
        resp  = requests.post(
            f"{_mpesa_base()}/mpesa/stkpush/v1/processrequest",
            json=payload,
            headers={"Authorization": f"Bearer {token}"},
            timeout=15,
        )
        resp.raise_for_status()
        data = resp.json()
    
        return {
            "success":            data.get("ResponseCode") == "0",
            "checkout_request_id": data.get("CheckoutRequestID"),
            "merchant_request_id": data.get("MerchantRequestID"),
            "response_code":       data.get("ResponseCode"),
            "message":             data.get("CustomerMessage", data.get("ResponseDescription")),
            "sandbox":             os.environ.get("MPESA_SANDBOX", "true").lower() == "true",
        }
  • The tool registration decorator using @mcp.tool with annotations. This is where 'mpesa_stk_push' is registered as an MCP tool on the FastMCP server instance.
    @mcp.tool(annotations={
        'title': 'M-Pesa STK Push',
        'readOnlyHint': False,
        'destructiveHint': True,
        'idempotentHint': False,
        'openWorldHint': True,
    })
  • Helper function that obtains an OAuth access token from Safaricom's API, used by mpesa_stk_push to authenticate the STK Push request.
    def _get_mpesa_token() -> str:
        if time.time() < _token_cache["expires_at"] - 30:
            return _token_cache["token"]  # type: ignore[return-value]
    
        sandbox = os.environ.get("MPESA_SANDBOX", "true").lower() == "true"
        base = "https://sandbox.safaricom.co.ke" if sandbox else "https://api.safaricom.co.ke"
    
        key    = os.environ["MPESA_CONSUMER_KEY"]
        secret = os.environ["MPESA_CONSUMER_SECRET"]
        creds  = base64.b64encode(f"{key}:{secret}".encode()).decode()
    
        resp = requests.get(
            f"{base}/oauth/v1/generate?grant_type=client_credentials",
            headers={"Authorization": f"Basic {creds}"},
            timeout=10,
        )
        resp.raise_for_status()
        data = resp.json()
        _token_cache["token"]      = data["access_token"]
        _token_cache["expires_at"] = time.time() + int(data["expires_in"])
        return _token_cache["token"]  # type: ignore[return-value]
  • Helper function that returns the base URL based on sandbox vs production mode, used by mpesa_stk_push when making the API call.
    def _mpesa_base() -> str:
        sandbox = os.environ.get("MPESA_SANDBOX", "true").lower() == "true"
        return "https://sandbox.safaricom.co.ke" if sandbox else "https://api.safaricom.co.ke"
  • Helper function that normalizes phone numbers to 12-digit Kenyan format (254XXXXXXXXX), used by mpesa_stk_push to format the customer's phone before sending to the API.
    def _normalize_phone(phone: str) -> str:
        """Normalize to 12-digit Kenyan format: 254XXXXXXXXX."""
        phone = phone.strip().lstrip("+")
        if phone.startswith("0"):
            phone = "254" + phone[1:]
        elif not phone.startswith("254"):
            phone = "254" + phone
        return phone
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already indicate destructiveHint=true and readOnlyHint=false. Description adds that customer enters PIN and the operation is async, requiring a subsequent query. This goes beyond basic annotation to explain customer interaction and completion pattern.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Three sentences, first sentence front-loads the core action. Every sentence adds value: action, customer flow, and async follow-up. No wasted words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Describes the return value (CheckoutRequestID) and async usage, even though output schema exists. With clear annotations and output schema, the description fully covers the tool's behavior and lifecycle.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents parameters. Description does not add further parameter details beyond what schema provides, so baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Starts with a specific verb 'Trigger' and resource 'M-Pesa STK Push'. Clearly states it sends a payment prompt to the customer's phone. Differentiates from sibling by mentioning mpesa_stk_query for tracking, distinguishing the two tools.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly states when to use mpesa_stk_query after 10-30 seconds, providing async guidance. Implicitly defines usage for initiating payment. Lacks explicit when-not-to-use conditions, but the context of siblings covers alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/gabrielmahia/mpesa-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server