M-Pesa Daraja

io.github.Mr-Macharia由 GitHub 账号 Mr-Macharia 发布v0.1.6更新于 Oct 29, 2026

Safaricom M-Pesa Daraja tools: STK Push, C2B, B2C, B2B, QR, Ratiba. Sandbox-first, idempotent.

概览

AI 生成的概览

把 Safaricom M-Pesa Daraja API 封装为工具,让助手在沙箱优先的前提下收款、查询结果并执行付款。

可以做什么
  • 通过 STK Push 收款,支持即发即忘、查询状态和等待最终结果
  • 注册 C2B 回调地址、在沙箱模拟付款并拉取交易记录
  • 发起 B2C、B2B、B2B Express、缴税与冲正付款,以及 Ratiba 定期扣款和 Bill Manager 账单
  • 查询交易状态与账户余额,并生成动态二维码 PNG 文件
  • 离线查询结果码、规范化手机号、生成 STK 密码并解析回调报文
  • 查看配置状态并校验凭据,且不返回任何密钥
适用场景
适合让助手在沙箱中验证 Daraja 集成、核对与支持 M-Pesa 交易,或在受控条件下从对话中发起收款和付款。开发者与学习者也可在正式上线前向安全的测试环境发送真实请求。
运行要求
通过 uvx 以 stdio 在本机运行(需安装 uv),或使用已安装的命令;仅限桌面端。需要 Daraja 应用的 Consumer Key 与 Secret,以及对应工具集所需的短码、STK passkey 和发起方凭据。回调需要公网 HTTPS 基础地址,可选内置接收器;HTTP 模式需要 Bearer 令牌。
安装前请注意
它可动用真实资金:生产环境的收款与付款需设置 DARAJA_ALLOW_LIVE_MONEY_MOVEMENT=true,建议保持沙箱并考虑 DARAJA_READ_ONLY、DARAJA_APPROVAL_THRESHOLD 与 DARAJA_ALLOWED_RECIPIENTS。它涉及 Daraja 密钥、passkey、发起方密码和回调令牌,请勿在对话或配置中暴露。回调可转发到你自己的端点,且 C2B 校验请求一律被接受。

安装

在 SourceWeft 中

  1. 打开 控制台中的 M-Pesa Daraja,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

[M-Pesa Daraja Agent Kit: Agent Skills and an MCP server for Safaricom's Daraja API. You ask your agent to charge a phone number; the customer gets an M-Pesa PIN prompt; the agent reports SUCCESS with the receipt number.]

mpesa-daraja

Renamed from mpesa-daraja-mcp in 0.1.5. The old package name still installs this one.

The MCP server in the M-Pesa Daraja Agent Kit. It lets an AI agent call Safaricom's Daraja API safely.

An MCP server that exposes Safaricom's Daraja APIs as tools, so an agent (Claude Code, Codex, Cursor, Gemini CLI, any MCP client) can collect payments, check whether they went through, and operate M-Pesa from a chat. It starts in the sandbox, and nothing live happens until you switch it on.

It pairs with the Agent Skills in the same kit: the skills teach an agent how to integrate M-Pesa, and this server lets it call Daraja. You can use either on its own.

Who it's for

  • Developers building payment integrations: ask your agent to run a request against the sandbox and read the real response.
  • Learners finding out how the Daraja API works: send real requests to a safe test environment and see what comes back.
  • Businesses and teams that want an AI agent to handle payments: collecting them, checking whether they went through, and reconciling them.

Install

Let your agent do it. Paste this into Claude Code, Codex, Cursor, Gemini CLI or any coding agent:

text
Add the M-Pesa Daraja MCP server to yourself, named "mpesa", with the command: uvx mpesa-daraja-mcpIt needs no keys in your config. If uv is missing, tell me how to install it first.Don't ask me for my Daraja keys. Tell me to run `uvx mpesa-daraja-mcp init` in my own terminal,which saves them privately, then to restart you.After I restart you, call mpesa_check_credentials and tell me if everything works.

Or do it yourself. You need uv. The wizard asks for your Daraja keys (secrets are typed hidden), checks them live with Safaricom, saves them to a file only you can read, and registers the server with Claude Code, Codex, Gemini CLI or Cursor:

bash
uvx mpesa-daraja-mcp init

Then restart your agent and ask: "Check my M-Pesa credentials, then send a KES 1 STK push to 0712345678 and tell me when it's paid." The full Agent Kit, with the skills and more examples, is in the main README.

Tools

ToolDaraja APIMoves money
mpesa_explain_code— offline error/result code lookup
mpesa_normalize_phone— offline 07… → 2547…
mpesa_generate_stk_password— offline Password + EAT Timestamp
mpesa_parse_callback— offline parse of any callback payload
mpesa_setup_status— offline: what's configured and missing per toolset (no values)
mpesa_check_credentialsOAuth token (never returned)
mpesa_get_resultFinal status by idempotency key or any Daraja ID (from captured callbacks; STK falls back to STK Query)
mpesa_stk_push_and_waitM-Pesa Express: push, then wait for callback / poll query; returns SUCCESS, FAILED or UNKNOWN✅
mpesa_stk_push / mpesa_stk_queryM-Pesa Express, fire-and-forget / status✅ /
mpesa_c2b_register_urls / mpesa_c2b_simulateC2B v2 (simulate = sandbox only)
mpesa_pull_transactionsPull Transactions query
mpesa_b2c_paymentB2C v3, B2Pochi✅
mpesa_b2b_paymentBusinessPayBill, BusinessBuyGoods, BusinessPayToBulk (B2C top-up), PayTaxToKRA✅
mpesa_b2b_express_checkoutB2B USSD push✅
mpesa_transaction_status / mpesa_account_balanceStatus / Balance (async result)
mpesa_reverse_transactionReversal✅
mpesa_generate_dynamic_qrDynamic QR, saved as a PNG file (path returned, not the image)
mpesa_ratiba_create_standing_orderM-Pesa Ratiba✅
mpesa_bill_manager_optin / mpesa_bill_manager_send_invoice / mpesa_bill_manager_cancel_invoiceBill Manager

Tool annotations mark money-moving tools as destructiveHint, so MCP clients ask for approval.

Safety

  • Defaults to the sandbox.
  • In production, money-moving tools refuse to run unless DARAJA_ALLOW_LIVE_MONEY_MOVEMENT=true.
  • Optional guardrails, all off until set:
    • DARAJA_READ_ONLY=true hides every tool that moves money or writes. Use it for support bots, reconciliation and learning.
    • DARAJA_APPROVAL_THRESHOLD=5000: B2C, B2B, tax and reversals above KES 5,000 pause for a yes/no in the chat (MCP elicitation). Clients that can't show the prompt get a refusal, and nothing is sent. Collections (STK, B2B Express, Ratiba) never prompt, because the payer enters their own PIN.
    • DARAJA_ALLOWED_RECIPIENTS=0712345678,600000: payouts may go only to these phones and shortcodes.
    • For a B2C refund, pass refund_of with the original M-Pesa receipt; it appears in the approval prompt and the remarks.
  • Callback URLs must be HTTPS; C2B URLs with mpesa/safaricom in them are rejected up front.
  • Tokens and secrets are never returned in tool output.
  • Responses with ResponseCode "0" are tagged _note: ACCEPTED for processing only, so the agent does not report them as completed payments.
  • Idempotent money tools. Each request is stored under an idempotency key. Repeating the key returns the stored request (duplicate: true) instead of paying again.
    • Only a definitively FAILED request is re-sent.
    • ACCEPTED or UNKNOWN requests (queue timeouts, network errors) are never re-sent until their result is known.
    • B2C, B2B and B2B Express require an explicit idempotency_key, e.g. refund-order-1042. Reversal, tax and Ratiba derive one from the transaction ID, the PRN and phone + name respectively. For STK the key is optional.

Configuration

VariableRequiredNotes
DARAJA_ENVsandbox (default) or production
DARAJA_CONSUMER_KEY, DARAJA_CONSUMER_SECRET✅From your Daraja app
DARAJA_SHORTCODEmost toolsPaybill / store number (174379 in sandbox)
DARAJA_PASSKEYSTKLipa na M-Pesa passkey
DARAJA_INITIATOR_NAMEB2C/B2B/status/balance/reversalAPI operator username
DARAJA_SECURITY_CREDENTIALsamePre-encrypted credential, or set the next two
DARAJA_INITIATOR_PASSWORD + DARAJA_CERT_PATHServer encrypts the password with the cert at startup
DARAJA_CALLBACK_BASE_URLe.g. https://abc.ngrok-free.app; tools append /mpesa/stk/callback, /mpesa/b2c/result, …
DARAJA_ALLOW_LIVE_MONEY_MOVEMENTtrue to allow production charges/payouts
DARAJA_CALLBACK_LISTENe.g. 127.0.0.1:8787: starts the built-in callback receiver
DARAJA_CALLBACK_TOKENwith receiver16+ random characters. Callback URLs become <base>/cb/<token>/…
DARAJA_STATE_DBSQLite file for requests and results (default ~/.mpesa-mcp/state.db)
DARAJA_TOOLSETSComma list of stk,c2b,payouts,ops,qr,ratiba,billmanager (core is always on). Default: all
DARAJA_READ_ONLYtrue hides every tool that moves money or writes
DARAJA_APPROVAL_THRESHOLDPayouts above this many shillings need a yes in the chat
DARAJA_ALLOWED_RECIPIENTSComma list of phones/shortcodes that payouts may go to
DARAJA_OUTPUT_DIRWhere QR PNGs are saved (default ~/.mpesa-mcp/qr)
DARAJA_FORWARD_URLYour app's endpoint. Each callback is POSTed on to it, signed. See forwarding
DARAJA_FORWARD_SECRETwith forwarding16+ random characters, used for the X-Mpesa-Signature HMAC
DARAJA_MCP_TOKENHTTP mode32+ random characters; clients send Authorization: Bearer <token>
DARAJA_MCP_HOST, DARAJA_MCP_PORTHTTP mode bind address and port (default 127.0.0.1:8000)

Commands and configuration files

Install once with uv tool install mpesa-daraja-mcp to get the mpesa command (or prefix any command with uvx mpesa-daraja-mcp instead of mpesa):

bash
mpesa init                 # guided: keys (hidden input), live check, save, register with your agentsmpesa status               # what's configured (masked), the guardrails, and a live key checkmpesa dev                  # callback receiver + tunnel (cloudflared or ngrok) + a live log of callbacksmpesa serve [--http]       # the MCP server: stdio for local agents, HTTP for remote onesmpesa up --domain pay.example.com   # self-host with Docker and automatic HTTPSmpesa pay stk 0712345678 10 --ref order-42     # waits for the PIN and shows the outcomempesa pay b2c 0712345678 500 --key refund-42 --refund-of NLJ7RT61SVmpesa result <id>   ·   mpesa balance   ·   mpesa explain 1032mpesa skills install       # copy the Agent Skills into Claude Code, Codex, Cursor, …mpesa upgrade

Every data command takes --json, and mpesa --verbose … logs each HTTP request to Daraja. A failed STK Push shows the --key to retry it with. Payments use the same guardrails as the MCP tools, and approvals are asked in the terminal. uvx mpesa-daraja-mcp with no arguments is the MCP server on stdio, which is what your agent runs.

The server needs no flags or environment variables in your agent's config. Settings are read in this order, highest first:

  1. Environment variables, e.g. from the client's env block.
  2. A project .env in the folder the agent starts the server in, or the file named by DARAJA_DOTENV. Only DARAJA_* lines are read.
  3. The user config file that setup writes: ~/.config/mpesa-daraja-mcp/config.env (Windows: %APPDATA%\mpesa-daraja-mcp\config.env; override the folder with DARAJA_CONFIG_DIR). It is readable only by you.

The server starts even when unconfigured. Tools then explain what's missing, and mpesa_setup_status lists the gaps for each toolset without revealing any values.

To register by hand: claude mcp add --scope user mpesa -- uvx mpesa-daraja-mcp. Every other agent is covered in docs/clients.md. The mpesa-daraja and mpesa-mcp commands are aliases.

Remote access (HTTP mode)

mpesa serve --http serves MCP at /mcp and Daraja callbacks at /cb/<token>/… on one port, for n8n, cloud agents and teammates. It needs DARAJA_MCP_TOKEN, and starts read-only with every payout needing approval unless you say otherwise. Docker, HTTPS and n8n guides: https://github.com/Mr-Macharia/mpesa-daraja-skills-and-mcp/blob/main/docs/self-hosting.md

Results and callbacks

Every money or async tool returns one shape:

json
{"status": "ACCEPTED | SUCCESS | FAILED | UNKNOWN", "message": "...", "idempotency_key": "...", "duplicate": false, "ids": {"checkout_request_id": "..."}, "receipt": "...", "result_code": "...", "explanation": "...", "raw": {}}

To let the agent see final results, enable the built-in receiver:

bash
export DARAJA_CALLBACK_LISTEN=127.0.0.1:8787export DARAJA_CALLBACK_TOKEN=$(python -c "import secrets; print(secrets.token_urlsafe(24))")ngrok http 8787                        # sandbox; use a reverse proxy with TLS in productionexport DARAJA_CALLBACK_BASE_URL=https://<tunnel-host>

Callbacks are stored in DARAJA_STATE_DB:

  • mpesa_get_result(id) reads them.
  • mpesa_stk_push_and_wait returns the final outcome in one call.
  • Queue-timeout callbacks are recorded as UNKNOWN.
  • C2B validation requests are always accepted. Use your own receiver if you need to reject payments.

Without the receiver, mpesa_stk_push_and_wait still works through STK Query. For other APIs, paste a received payload into mpesa_parse_callback.

Load only the tools you need

Every tool the server offers takes up space in your agent's context, even when it's never called. Set DARAJA_TOOLSETS to the groups you use, and the agent sees only those tools. The basic tools (core) are always on; leave the setting unset to load everything.

SettingYou getGood for
unset (default)all 24 toolsexploring everything
stkthe basic tools plus the 3 STK Push toolsa shop that only takes STK payments
stk,payoutsthe above, plus B2C, B2B and B2B Expressa platform that collects and pays out
stk,c2b,opsSTK, C2B, then transaction status, balance and reversalreconciliation and support

The groups are stk, c2b, payouts, ops, qr, ratiba and billmanager.

Use from LangChain, the OpenAI Agents SDK, Agno, Google ADK, CrewAI or your own agent

The same tools and guardrails work without a server: from mpesa_mcp.agent import mpesa_tools, or the adapters in mpesa_mcp.integrations (pip install "mpesa-daraja-mcp[langchain]", or [openai-agents], [agno], [google-adk], [crewai]). See docs/agent-frameworks.md.

Development

bash
pip install -e ".[dev]"pytest

Tests use respx to mock Daraja. Nothing hits the network.

License

MIT © 2026 Mr-Macharia. An independent open-source project, not affiliated with or endorsed by Safaricom PLC. M-Pesa and Daraja are trademarks of Safaricom PLC.

来源:mcp-server/README.md,提交 3942fb3

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

4
  1. v0.1.6最新Oct 29, 2026
  2. v0.1.4Oct 25, 2026
  3. v0.1.3Oct 21, 2026
  4. v0.1.1Oct 20, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分