Skip to main content
Glama

M-Pesa STK Query

mpesa_stk_query
Read-onlyIdempotent

Query the status of an M-Pesa STK Push request. Poll 10-30 seconds after initiating the push. Result codes: 0 indicates success, 1032 user cancelled, 1037 timed out.

Instructions

Check the status of an STK Push request. Poll this 10-30 seconds after calling mpesa_stk_push. ResultCode 0 = success, 1032 = cancelled by user, 1037 = timed out.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
checkout_request_idYesCheckoutRequestID from mpesa_stk_push response

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The mpesa_stk_query function that executes the STK push query logic. It takes a checkout_request_id, builds the payload with BusinessShortCode, Password, Timestamp, and CheckoutRequestID, then calls the Safaricom Daraja /mpesa/stkpushquery/v1/query API and returns the status (success, result_code, status description).
    def mpesa_stk_query(
        checkout_request_id: Annotated[str, "CheckoutRequestID from mpesa_stk_push response"],
    ) -> dict:
        """
        Check the status of an STK Push request.
        Poll this 10-30 seconds after calling mpesa_stk_push.
        ResultCode 0 = success, 1032 = cancelled by user, 1037 = timed out.
        """
        shortcode = os.environ["MPESA_SHORTCODE"]
        passkey   = os.environ["MPESA_PASSKEY"]
        timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        password  = base64.b64encode(f"{shortcode}{passkey}{timestamp}".encode()).decode()
    
        payload = {
            "BusinessShortCode":  shortcode,
            "Password":           password,
            "Timestamp":          timestamp,
            "CheckoutRequestID":  checkout_request_id,
        }
    
        token = _get_mpesa_token()
        resp  = requests.post(
            f"{_mpesa_base()}/mpesa/stkpushquery/v1/query",
            json=payload,
            headers={"Authorization": f"Bearer {token}"},
            timeout=10,
        )
        resp.raise_for_status()
        data = resp.json()
    
        result_code = int(data.get("ResultCode", -1))
        status_map  = {
            0:    "SUCCESS",
            1:    "INSUFFICIENT_FUNDS",
            1001: "LOCKED — retry in 30s",
            1019: "EXPIRED — re-initiate",
            1032: "CANCELLED_BY_USER",
            1037: "TIMEOUT",
            2001: "WRONG_PIN",
        }
    
        return {
            "success":      result_code == 0,
            "result_code":  result_code,
            "status":       status_map.get(result_code, f"UNKNOWN ({result_code})"),
            "description":  data.get("ResultDesc"),
        }
  • The @mcp.tool decorator registering mpesa_stk_query as an MCP tool with annotations including title 'M-Pesa STK Query', readOnlyHint=True, idempotentHint=True.
    @mcp.tool(annotations={
        'title': 'M-Pesa STK Query',
        'readOnlyHint': True,
        'destructiveHint': False,
        'idempotentHint': True,
        'openWorldHint': True,
    })
  • The _get_mpesa_token helper used by mpesa_stk_query to obtain an OAuth bearer token for authenticating with the Daraja API.
    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]
  • The _mpesa_base helper returns the correct base URL (sandbox vs production) used by mpesa_stk_query to construct the API endpoint.
    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"
  • Smoke test verifying that 'mpesa_stk_query' is among the registered tool names.
    def test_tools_registered():
        import asyncio
        from mpesa_mcp import mcp
        tools = asyncio.run(mcp.list_tools())
        names = [t.name for t in tools]
        expected = [
            "mpesa_stk_push",
            "mpesa_stk_query",
            "mpesa_transaction_status",
            "sms_send",
            "airtime_send",
        ]
        for name in expected:
            assert name in names, f"Tool '{name}' not registered. Found: {names}"
Behavior4/5

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

Description adds valuable behavioral details beyond annotations: polling timing and specific result codes (0, 1032, 1037). Annotations already indicate readOnly and idempotent, so no contradiction.

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 concise sentences: purpose first, then timing, then codes. Every sentence adds essential information with no waste.

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

Completeness4/5

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

Given output schema exists (not shown but mentioned), description covers key usage (timing, codes). Could briefly mention other possible result codes or behavior, but overall sufficient.

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 coverage is 100% with a single parameter clearly described. Description does not add new meaning beyond what the schema already provides, so baseline 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?

Description explicitly states 'Check the status of an STK Push request', clearly identifying the verb and resource. It distinguishes from sibling tools like mpesa_stk_push (initiates) and mpesa_transaction_status (general status).

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?

Description provides explicit timing guidance ('Poll this 10-30 seconds after calling mpesa_stk_push') and lists key result codes, aiding in when to use. However, it does not explicitly exclude other scenarios or mention alternative tools.

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