Skip to main content
Glama
stellar-mcp

stellar-mcp

by ijele-don
README.md
# stellar-mcp

[![CI](https://github.com/ijele-don/stellar-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/ijele-don/stellar-mcp/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)
[![Node.js >= 20](https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen.svg)](https://nodejs.org/)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue.svg)](https://www.typescriptlang.org/)
[![MCP](https://img.shields.io/badge/Protocol-MCP%201.0-purple.svg)](https://modelcontextprotocol.io/)

A lightweight, **zero-CLI-dependency** Model Context Protocol (MCP) server that gives AI coding assistants (Claude Code, Cursor, Windsurf, Claude Desktop) native, real-time access to the **Stellar network** and **Soroban smart contracts**—focused on **debugging, diagnostics, and safe-by-default workflows**.

---

## Table of Contents

- [Why `stellar-mcp`?](#why-stellar-mcp)
- [Architecture](#architecture)
- [Installation & IDE Setup](#installation--ide-setup)
- [Configuration & Networks](#configuration--networks)
- [Tools Reference (12)](#tools-reference-12)
- [MCP Resources & Prompts](#mcp-resources--prompts)
- [Security & Safety Model](#security--safety-model)
- [Real-World IDE Workflows](#real-world-ide-workflows)
- [Project Structure](#project-structure)
- [Development, Testing & CI](#development-testing--ci)
- [Roadmap](#roadmap)
- [License & Attribution](#license--attribution)

---

## Why `stellar-mcp`?

Working on Soroban often means context-switching between your IDE, `stellar` CLI, block explorers, and raw XDR decoders. `stellar-mcp` eliminates that friction:

- **Zero External CLI Dependency:** No `stellar` CLI binary required. Contract WASM `contractspecv0` custom sections, XDR structures, and RPC/Horizon queries are parsed natively in Node.js via `@stellar/stellar-sdk` and `WebAssembly.Module`.
- **Deep Soroban Diagnostics:** Translates opaque host errors (`Error(Contract, #4)`, `Error(Storage, MissingValue)`, `Error(Auth, InvalidAction)`, `Error(Budget, ExceededLimit)`) into root-cause explanations and fixes, and resolves custom `#[contracterror]` variant names directly from deployed WASM specs.
- **Storage & TTL Health:** Inspects contract instance and keyed storage byte sizes, computes remaining TTL in ledgers and days (~17,280 ledgers/day), and flags oversized or expiring/archived entries.
- **Safe-by-Default Guardrails:** Mainnet is strictly **read-only and simulate-only** by default (`ALLOW_MAINNET_WRITES=false`). `build_transaction` outputs unsigned XDR with an automatic `XdrInspector` security audit.
- **Clean Context Hygiene:** Converts `BigInt` values safely, truncates oversized JSON responses at 32,000 characters, and writes all logs strictly to `stderr` so MCP `stdout` JSON-RPC frames are never corrupted.

---

## Architecture

```
+-------------------------------------------------------------------+
|  AI Coding Assistant (Claude Code / Cursor / Windsurf / Desktop)  |
+---------------------------------+---------------------------------+
                                  |  MCP over stdio (JSON-RPC)
                                  v
+-------------------------------------------------------------------+
|  stellar-mcp (src/index.ts)                                       |
|  +-- Tools (src/registry.ts)         -> 12 validated Zod tools    |
|  +-- Resources (src/resources.ts)    -> network, contract, acct   |
|  +-- Prompts (src/prompts.ts)        -> debug, audit, review      |
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|  Pure-SDK Services (src/services/)                                |
|  +-- networks.ts       -> Presets, cached clients, write guard    |
|  +-- contract-spec.ts  -> WASM contractspecv0 + SAC + 5m cache    |
|  +-- xdr-decoder.ts    -> ScVal, LedgerKey, Envelope, HostErrors  |
|  +-- inspector.ts      -> XdrInspector security/risk analyzer     |
+---------------------------------+---------------------------------+
                                  |  HTTPS / HTTP (local)
          +-----------------------+-----------------------+
          v                                               v
+-------------------+                           +-------------------+
|    Soroban RPC    |                           |    Horizon API    |
+-------------------+                           +-------------------+
```

---

## Installation & IDE Setup

### Prerequisites

- **Node.js `>= 20.0.0`**

### Option A: Run from Source (Recommended while developing)

```bash
git clone git@github-ijele-don:ijele-don/stellar-mcp.git
cd stellar-mcp
npm install
npm run build
```

### Option B: Run via `npx` (Once published)

```bash
npx -y stellar-mcp
```

### Claude Code

```bash
# Using local build
claude mcp add stellar-mcp -- node /absolute/path/to/stellar-mcp/dist/index.js

# Or via npx
claude mcp add stellar-mcp -- npx -y stellar-mcp
```

### Cursor (`~/.cursor/mcp.json`) / Windsurf (`~/.codeium/windsurf/mcp_config.json`) / Claude Desktop

```json
{
  "mcpServers": {
    "stellar-mcp": {
      "command": "node",
      "args": ["/absolute/path/to/stellar-mcp/dist/index.js"],
      "env": {
        "STELLAR_NETWORK": "testnet",
        "ALLOW_MAINNET_WRITES": "false",
        "LOG_LEVEL": "info"
      }
    }
  }
}
```

---

## Configuration & Networks

Copy `.env.example` to `.env` if running locally, or pass environment variables in your MCP client config.

### Environment Variables

| Variable | Default | Description |
| --- | --- | --- |
| `STELLAR_NETWORK` | `testnet` | Default network: `mainnet`, `testnet`, `futurenet`, `local`, or `custom` |
| `HORIZON_URL` | preset | Custom Horizon URL (required for `custom` if `SOROBAN_RPC_URL` is unset) |
| `SOROBAN_RPC_URL` | preset | Custom Soroban RPC URL |
| `NETWORK_PASSPHRASE` | preset | Custom network passphrase |
| `ALLOW_MAINNET_WRITES` | `false` | Must be `"true"` to allow `submit_transaction` on `mainnet` |
| `STELLAR_SECRET_KEY` | unset | Optional `S...` secret key for in-process signing when `sign: true` |
| `LOG_LEVEL` | `info` | `error`, `warn`, `info`, or `debug` (writes strictly to `stderr`) |

### Network Presets

| Network | Horizon URL | Soroban RPC URL | Passphrase |
| --- | --- | --- | --- |
| `mainnet` | `https://horizon.stellar.org` | `https://soroban-rpc.stellar.org` | `Public Global Stellar Network ; September 2015` |
| `testnet` | `https://horizon-testnet.stellar.org` | `https://soroban-testnet.stellar.org` | `Test SDF Network ; September 2015` |
| `futurenet` | `https://horizon-futurenet.stellar.org` | `https://rpc-futurenet.stellar.org` | `Test SDF Future Network ; October 2022` |
| `local` | `http://localhost:8000` | `http://localhost:8000/soroban/rpc` | `Standalone Network ; February 2017` |

Every tool also accepts an optional `network` parameter to override the configured default per call.

---

## Tools Reference (12)

### Network & Ledger Inspection

| Tool | Required Inputs | Optional Inputs | Returns |
| --- | --- | --- | --- |
| `get_network_status` | — | `network` | RPC health, latest ledger sequence, protocol version, endpoints, and `mainnet_writes_allowed` |
| `get_account` | `account_id` (`G...`) | `asset_code`, `asset_issuer`, `network` | XLM & issued asset balances, sequence number, thresholds, and signers |
| `get_transaction` | `tx_hash` (64-char hex) | `network` | Status, ledger, decoded envelope, return value, and diagnostic events (RPC + Horizon fallback) |
| `get_contract_events` | `contract_id` (`C...`) | `start_ledger`, `limit` (1–100, default 20), `network` | Recent contract events with decoded `topics` and `value` |

### Soroban Diagnostics & Introspection

| Tool | Required Inputs | Optional Inputs | Returns |
| --- | --- | --- | --- |
| `fetch_contract_spec` | `contract_id` (`C...`) | `network` | Decoded `contractspecv0` ABI: `functions`, `structs`, `enums`, `unions`, `error_codes` (plus built-in SEP-41 spec for Stellar Asset Contracts) |
| `simulate_transaction` | `xdr` (base64 envelope) | `contract_id`, `network` | `status` (`success` \| `restore_needed` \| `error`), decoded `return_value`, CPU/memory `cost`, `min_resource_fee`, decoded `footprint`, `events`, `restore_preamble`, or structured `diagnosis` |
| `diagnose_soroban_error` | `error_message` | `contract_id`, `network` | Error `category`, `code`, root-cause `explanation`, `suggested_fix`, and resolved `#[contracterror]` variant name when `contract_id` is provided |
| `analyze_contract_storage` | `contract_id` (`C...`) | `additional_keys` (up to 50 base64 `LedgerKey` XDRs), `size_threshold_bytes` (default 1024), `network` | Per-entry byte size, `storage_type`, `ttl_remaining_ledgers`, `ttl_remaining_days`, `ttl_status` (`healthy` \| `expiring_soon` \| `expired`), and optimization recommendations |

### XDR Decoding & Security

| Tool | Required Inputs | Optional Inputs | Returns |
| --- | --- | --- | --- |
| `inspect_xdr` | `xdr` (base64 envelope) | `network` | Decoded transaction summary + `XdrInspector` security report (`is_safe`, `risk_level`, `findings`) |
| `decode_xdr` | `xdr`, `type` | `network` | Decoded JSON for `TransactionEnvelope`, `ScVal`, `LedgerKey`, `LedgerEntryData`, `DiagnosticEvent`, or `SorobanTransactionData` |

### Safe Transaction Workflows

| Tool | Required Inputs | Optional Inputs | Returns |
| --- | --- | --- | --- |
| `build_transaction` | `source_account` (`G...`), `operations` (`payment`, `change_trust`, `invoke_contract`) | `memo`, `fee_stroops`, `timeout_seconds` (default 300), `network` | **Unsigned** `unsigned_xdr`, fetched sequence number, and `XdrInspector` safety report |
| `submit_transaction` | `xdr` (base64 envelope) | `sign` (default `false`), `wait_for_result` (default `true`), `wait_timeout_ms` (default 20000), `network` | Submission status, `hash`, and confirmed `ledger` (RPC with Horizon fallback). **Blocked on `mainnet` unless `ALLOW_MAINNET_WRITES=true`.** |

---

## MCP Resources & Prompts

### Resources & Resource Templates

| URI / Template | Description |
| --- | --- |
| `stellar://network/status` | Live RPC health, latest ledger, protocol version, and mainnet write-policy state |
| `soroban://contract/{contract_id}/spec` | Decoded ABI/spec (`functions`, `structs`, `enums`, `error_codes`) for a deployed contract |
| `stellar://account/{account_id}` | Account balances, sequence, thresholds, and signers |

### Prompts

| Prompt | Arguments | Purpose |
| --- | --- | --- |
| `debug-failed-tx` | `tx_hash?`, `error_message?`, `contract_id?`, `network?` | Guides the assistant through `get_transaction`, `diagnose_soroban_error`, `fetch_contract_spec`, and `get_contract_events` |
| `audit-contract-storage` | `contract_id`, `network?` | Audits contract spec, entry byte sizes, TTL health, and storage architecture |
| `review-xdr-safety` | `xdr`, `network?` | Runs `inspect_xdr` and `simulate_transaction` before signing or submitting |

---

## Security & Safety Model

1. **Read-Only Mainnet Default:** `assertWriteAllowed` in [src/services/networks.ts](file:///home/escelit/Desktop/devprom6/stellar-mcp/src/services/networks.ts) throws a `SafetyPolicyError` on any `submit_transaction` targeting `mainnet` unless `ALLOW_MAINNET_WRITES=true` is explicitly set.
2. **Unsigned Transaction Building:** `build_transaction` never requires a private key—it produces unsigned XDR for simulation or external wallet signing (e.g., Freighter or hardware wallets).
3. **Automatic XDR Risk Auditing:** `XdrInspector` ([src/services/inspector.ts](file:///home/escelit/Desktop/devprom6/stellar-mcp/src/services/inspector.ts)) checks every built or inspected transaction:
   - `HIGH`: `ACCOUNT_MERGE`, `SIGNER_CHANGE` (`setOptions.signer`), `CLAWBACK`
   - `MEDIUM`: `EXCESSIVE_FEE` (>100x `BASE_FEE` per op), `THRESHOLD_CHANGE`, `REVOKE_SPONSORSHIP`
   - `LOW`: `INVOKE_HOST_FUNCTION` (advises simulation first), `CHANGE_TRUST`
4. **Secret Redaction:** `pino` logger redacts `STELLAR_SECRET_KEY`, `secret`, `secretKey`, and `privateKey`, and writes strictly to `stderr`.

---

## Real-World IDE Workflows

- **Debug a failed contract call:**
  > *"Transaction `a1b2...` failed on testnet with `Error(Contract, #4)` on contract `C...`. Diagnose why it failed and check recent contract events."*
- **Audit storage & rent before mainnet deploy:**
  > *"Audit contract `C...` on testnet: fetch its spec, check instance storage size, and tell me how many days of TTL remain."*
- **Verify an unsigned XDR before signing:**
  > *"Inspect this base64 XDR for risky operations and simulate it on testnet to check the auth tree and resource fee."*

---

## Project Structure

```
stellar-mcp/
├── .github/workflows/ci.yml        # GitHub Actions CI (Node 20 & 22)
├── src/
│   ├── index.ts                    # MCP stdio server entry point
│   ├── config.ts                   # Zod-validated env configuration
│   ├── errors.ts                   # Typed StellarMcpError hierarchy
│   ├── logger.ts                   # stderr-only pino logger with redaction
│   ├── registry.ts                 # Single source of truth for all 12 tools
│   ├── resources.ts                # MCP resources & URI templates
│   ├── prompts.ts                  # Guided MCP debugging/audit prompts
│   ├── services/
│   │   ├── networks.ts             # Network presets, cached clients, write guard
│   │   ├── contract-spec.ts        # Native WASM contractspecv0 + SAC parser
│   │   ├── xdr-decoder.ts          # ScVal, LedgerKey, Envelope & error decoder
│   │   └── inspector.ts            # XdrInspector transaction risk analyzer
│   ├── tools/                      # 12 modular MCP tool implementations
│   └── utils/
│       └── json.ts                 # BigInt-safe JSON & 32k context truncation
├── tests/                          # Unit tests + gated live Testnet suite
├── .env.example
├── LICENSE
├── package.json
├── tsconfig.json
└── vitest.config.ts
```

---

## Development, Testing & CI

```bash
# Typecheck, build, and run offline unit tests
npm run typecheck
npm run build
npm test

# Run live Stellar Testnet integration tests (requires network access)
npm run test:testnet
```

- **Unit tests (`npm test`):** Offline, fast, and run automatically in [CI](.github/workflows/ci.yml) on Node 20 and 22.
- **Live Testnet suite (`npm run test:testnet`):** Verifies `get_network_status`, `fetch_contract_spec`, `analyze_contract_storage`, and live WASM `contractspecv0` parsing against `https://soroban-testnet.stellar.org`.

---

## Roadmap

- [ ] `build_restore_transaction` helper when `simulate_transaction` returns `restore_needed`
- [ ] Streamable HTTP transport alongside `stdio` for remote MCP clients
- [ ] Local Rust/TypeScript ABI drift checker comparing workspace contracts against deployed Testnet/Mainnet specs
- [ ] Publish to npm for zero-setup `npx -y stellar-mcp` usage

---

## License & Attribution

MIT License — see [LICENSE](./LICENSE).

Maintained by [@ijele-don](https://github.com/ijele-don). Originally inspired by [pulsar](https://github.com/benelabs/pulsar) (MIT, Copyright (c) 2026 pulsar community), rebuilt from the ground up with a zero-CLI-dependency core, Soroban diagnostics, MCP resources/prompts, and mainnet safety defaults.

TDQS

A3.7/5.0

Scored across 12 tools

Disambiguation4/5

Most tools have clearly distinct purposes tied to a specific resource or pipeline stage (simulate, build, submit, diagnose). The main overlap is between decode_xdr and inspect_xdr, both of which decode a TransactionEnvelope, but descriptions clarify that inspect_xdr adds a security audit while decode_xdr handles broader XDR types.

Naming Consistency4/5

Names consistently follow snake_case verb_noun form (get_account, simulate_transaction, build_transaction, submit_transaction). Minor deviation: retrieval verbs alternate between get_ (get_account, get_transaction, get_contract_events) and fetch_ (fetch_contract_spec), plus a couple of verb_xdr forms, but overall it is predictable.

Tool Count5/5

Twelve tools is well within the ideal range and each maps to a distinct stage of the Soroban workflow (inspect, decode, simulate, build, submit, diagnose). No filler or redundant tools are present.

Completeness4/5

The surface covers the core lifecycle well: network status, account/transaction lookup, contract spec, simulation, error diagnosis, XDR decode/audit, storage, events, and build/submit. Gaps remain around contract deployment (upload WASM, create contract) and richer transaction building (only payment, change_trust, invoke_contract), which agents may need to work around.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues