---
title: "MCP server"
description: "Expose an SmsClient over stdio or Streamable HTTP with @opencoredev/sms-sdk/mcp: zero dependencies, dry-run send previews by default."
---

{/* unreleased: remove when sms-sdk#6 ships */}
:::note[Coming in the next release, 0.2.0]
`@opencoredev/sms-sdk/mcp` and `sms-sdk mcp` ship in 0.2.0. The current npm version, 0.1.1, does not include them yet. Track it in [the release PR](https://github.com/opencoredev/sms-sdk/pull/6).
:::

`@opencoredev/sms-sdk/mcp` wraps an `SmsClient` in a zero-dependency Model Context Protocol (MCP) server over JSON-RPC 2.0 (`2025-06-18`, `2025-03-26`, and `2024-11-05`). Use it to give coding agents or internal tools structured SMS validation, segment estimation, message lookup, and guarded sending.

## Quick start (CLI stdio)

Start the stdio MCP server over whichever providers are configured in your environment:

```bash
npx @opencoredev/sms-sdk mcp
```

Or register it in an MCP client configuration (Claude Desktop, Cursor, or any `mcpServers` host):

```json
{
  "mcpServers": {
    "sms-sdk": {
      "command": "npx",
      "args": ["-y", "@opencoredev/sms-sdk", "mcp"],
      "env": {
        "TWILIO_ACCOUNT_SID": "AC...",
        "TWILIO_AUTH_TOKEN": "...",
        "TWILIO_FROM": "+15005550006"
      }
    }
  }
}
```

Live sending is disabled by default: `sms_send` returns a dry-run validation preview even if the caller passes `confirmSend: true`. Opt into live sending explicitly with `--allow-live-send`. See [CLI](/reference/doctor-cli#sms-sdk-mcp) for flags.

## Programmatic stdio server

```ts
import { createSmsMcpServer, createStdioLineWriter, serveSmsMcpStdio } from "@opencoredev/sms-sdk/mcp";
import { sms } from "./sms";

const server = createSmsMcpServer(sms, {
  name: "acme-sms",
  version: "1.0.0",
  allowLiveSend: false, // default; set true only when confirmed live sends are desired
});

const write = createStdioLineWriter(process.stdout);
try {
  await serveSmsMcpStdio(server, { input: process.stdin, write });
} finally {
  write.dispose();
}
```

`createSmsMcpServer(client, options?)` accepts:

| Option | Meaning |
| --- | --- |
| `name` | Reported as `serverInfo.name` in `initialize` (default `"sms-sdk"`). |
| `version` | Reported as `serverInfo.version` in `initialize` (default: package version). |
| `instructions` | Guidance returned to MCP clients in `initialize` (default: built-in safety summary). |
| `allowLiveSend` | Enables `client.send()` when `confirmSend: true` is passed on the tool call (default `false`). |
| `maxBatchConcurrency` | Maximum JSON-RPC batch items handled concurrently by `server.handle(batch)` directly, from `1` to `100` (default `16`). |

`createStdioLineWriter` wraps any Node or Bun writable stream with `"drain"` backpressure and stream `"error"` handling. `serveSmsMcpStdio` frames newline-delimited JSON-RPC messages, bounds message size (`maxMessageBytes`, default 1 MiB) and concurrency (`maxInFlight`, default 16; `maxQueued`, default 256), and honors `notifications/cancelled`.

## Streamable HTTP handler

Mount the stateless Web `Request -> Response` handler in Next.js, Hono, Bun, Deno, or Cloudflare Workers:

```ts
import { timingSafeEqual } from "node:crypto";
import { createSmsMcpHttpHandler, createSmsMcpServer } from "@opencoredev/sms-sdk/mcp";
import { sms } from "./sms";

const expectedToken = process.env.MCP_TOKEN;
if (!expectedToken) {
  throw new Error("MCP_TOKEN is required");
}
const expectedHeader = Buffer.from(`Bearer ${expectedToken}`);

function authorizeRequest(request: Request): boolean {
  const actual = request.headers.get("authorization");
  if (actual === null) return false;
  const actualBytes = Buffer.from(actual);
  return actualBytes.length === expectedHeader.length && timingSafeEqual(actualBytes, expectedHeader);
}

const server = createSmsMcpServer(sms, { allowLiveSend: false });

export const POST = createSmsMcpHttpHandler(server, {
  authorize: authorizeRequest,
  allowedOrigins: ["https://app.example.com"],
});
```

`authorize` must fail closed when credentials are missing or misconfigured (never fall back to an empty string) and runs before reading the request body. The example above uses `node:crypto`, `Buffer`, and `process.env`; on Cloudflare Workers, use `nodejs_compat` with a compatibility date of `2025-04-01` or later, or read `env.MCP_TOKEN` with Web Crypto (`crypto.subtle.timingSafeEqual`) on earlier dates. Unlisted `Origin` headers are rejected with `403` to block DNS rebinding; browser clients on another origin still need CORS headers in your hosting router. `maxBodyBytes` defaults to 1 MiB and `maxBatchConcurrency` bounds legacy JSON-RPC batch concurrency (default `16`, max `100`).

**Cancellation over HTTP:** `createSmsMcpServer` and `createSmsMcpHttpHandler` are stateless across separate HTTP requests. To cancel an in-flight call (including a live `sms_send` paused in a hook), abort the original HTTP request (`request.signal`), which returns `499`. A separate `notifications/cancelled` POST returns `202` and is ignored by the built-in server, so it will not stop a pending billable send from another HTTP request (only matching requests in the same legacy batch are suppressed before dispatch).

| Status | Meaning |
| --- | --- |
| `200` | JSON-RPC response (or `text/event-stream` when `Accept` prefers SSE). |
| `202` | Accepted JSON-RPC notification or client response (empty body). |
| `400` | Invalid JSON, invalid UTF-8, unreadable body, unsupported `MCP-Protocol-Version`, or batch request on `2025-06-18`. |
| `401` | `authorize` returned a value other than `true`. |
| `403` | Request `Origin` header is not in `allowedOrigins`. |
| `405` | Method other than `POST` (sets `Allow: POST`). |
| `406` | `Accept` header disallows both `application/json` and `text/event-stream`. |
| `413` | Request body exceeds `maxBodyBytes`. |
| `415` | `Content-Type` is not `application/json`. |
| `499` | Caller aborted `request.signal` before a response was produced. |
| `500` | `authorize` threw or the server produced an unrecoverable internal error. |

## Exposed tools

| Tool | Behavior |
| --- | --- |
| `sms_capabilities` | Read-only. Lists adapters, support status, and limits. |
| `sms_estimate_segments` | Read-only. Estimates GSM-7/UCS-2 segments locally. |
| `sms_validate` | Read-only. Runs `client.validate(input)` offline. |
| `sms_get_message` | Read-only. Queries delivery status via `getMessage()`. |
| `sms_send` | Dry-run by default. Validates locally; live send requires `allowLiveSend: true` and `confirmSend: true`. |

Errors from `SmsError` subclasses serialize through `error.toJSON()`, preserving `code`, `retrySafe`, and redacted `attempts` without exposing credentials or message bodies.

## Exports

- `createSmsMcpServer(client, options?)`
- `createStdioLineWriter(stream, options?)`
- `serveSmsMcpStdio(server, options)`
- `createSmsMcpHttpHandler(server, options)`
- `SUPPORTED_MCP_PROTOCOL_VERSIONS`, `isSupportedMcpProtocolVersion`, `JSON_RPC_ERROR_CODES`
- Types: `SmsMcpClient`, `SmsMcpServer`, `SmsMcpServerOptions`, `SmsMcpRequestContext`, `SmsMcpResponse`, `SmsMcpStdioOptions`, `StdioWritableStream`, `StdioLineWriter`, `StdioLineWriterOptions`, `SmsMcpHttpOptions`, `McpProtocolVersion`, `JsonRpcId`
