Framework for building MCP (Model Context Protocol) servers with built-in telemetry, introspection, agent feedback, and a backend abstraction layer.
somamcp builds on the official MCP TypeScript SDK 2.x behind a BackendAdapter interface — giving you a stable API surface, automatic telemetry, gateway-based server composition, identity/health endpoints with sensible security defaults, and HTTP artifacts out of the box. One endpoint serves both the 2026-07-28 protocol revision and 2025-era clients.
The main entry, somamcp, uses web-standard APIs only, so it runs on Cloudflare Workers without nodejs_compat, and on Deno, Bun and Node. somamcp/node adds what only Node can do: listening on a port, stdio, file telemetry, and reading content from a path. Coming from 1.x? See Migrating from 1.x.
- Both protocol eras — the
2026-07-28revision that current Claude clients request first, and the 2025initializehandshake, from one endpoint - Runs anywhere — the main entry is WinterTC-only (Workers, Deno, Bun, Node);
somamcp/nodeadds a port listener and stdio - Backend abstraction — framework-agnostic
BackendAdapterinterface; swap the underlying MCP implementation without changing consumer code - Structured telemetry — pluggable
TelemetryCollectorwith console, file (NDJSON), composite, and functype-log adapters - OpenTelemetry tracing —
somamcp/otelopens a span around each tool call, and a trace crosses gateways to the servers behind them - Error classification & enrichment — errors are auto-classified (validation / execution / timeout / gateway / auth / not_found / internal) with actionable suggestions for LLMs
- Per-tool capture config — configure input/output capture levels, field redaction, and output size limits per tool
- Gateway system — connect to remote MCP servers and proxy their tools as local tools
- Identity & build info —
infoMCP tool returns name, version, build commit, runtime, and capability counts; auto-populated fromSOMAMCP_BUILD_*env vars - Two-tier health — public
/health(minimal, for Docker/k8s probes) + protected/health/detail(full operational state) - Protected artifacts —
protected: trueon any artifact reuses the server'sauthenticatecallback; dashboard and/infoprotected by default - Method-aware protected routes —
addRoute({ method, path, protected, handler })for customPOST/PUT/etc. endpoints behind the sameauthenticategate - Agent feedback tool —
createFeedbackToolposts agent-reported issues to GitHub or any webhook, with automatic credential/PII redaction - HTTP dashboard — auto-generated overview at
/dashboard(protected) - Functional style — powered by functype (
Ref,Try,Either)
pnpm add somamcp
# or
npm install somamcpOn Node, import from somamcp/node and start a transport:
import { createServer } from "somamcp/node"
import { z } from "zod"
const server = createServer({
name: "my-server",
version: "1.0.0",
})
server.addTool({
name: "greet",
description: "Greet someone by name",
parameters: z.object({ name: z.string() }),
execute: async ({ name }) => `Hello, ${name}!`,
})
await server.start({ transportType: "stdio" })
// or: await server.start({ transportType: "httpStream", httpStream: { port: 3000 } })On Cloudflare Workers (or any runtime with fetch), import from somamcp and serve requests:
import { createServer } from "somamcp"
const server = createServer({ name: "my-worker", version: "1.0.0" })
// ...addTool as above
export default { fetch: (request: Request) => server.fetch(request) }instructions is what a client reads about the server when it connects. It's a string, or a function of the caller's session, so each caller can get its own:
const server = createServer<Viewer>({
authenticate: verifyBearer,
instructions: async (viewer) => instructionsFor(await conventionsOf(viewer)),
name: "notes",
version: "1.0.0",
})- Both protocol eras. It's sent in the
initializeresult to 2025 clients and theserver/discoverresult to 2026-07-28 clients. - No session means
undefined. The function getsundefinedwhen the server has noauthenticate, or on stdio without one. On stdio,authenticateruns once, with no request, and the function gets what it resolved. - When it runs. On stdio, each time the connection builds a server: normally once, and twice when a client probes with
server/discoverand then falls back toinitialize. Over HTTP, per request: on 2026-07-28 clients only forserver/discover, which names its method in a header, and on 2025 clients for every request, because their method is only in the body. Cache in the function if the lookup is costly. - A failure fails the request. If the function throws, rejects or returns something other than a string, the request gets a JSON-RPC internal error (HTTP 500 over HTTP), and the cause goes to
logger, so a client never connects with its instructions missing. On 2025 clients that includes tool calls. The client never sees the cause. - Declare the parameter as
T | undefined. The type checker accepts a function that takesTalone, to keepServerConfig<T>assignable as before, but it can still getundefined. - An empty string means no instructions.
SomaMCP auto-registers one MCP introspection tool and three HTTP endpoints:
| Surface | Default path / name | Protected | Returns |
|---|---|---|---|
| MCP tool | info |
n/a | { name, version, build, runtime, capabilities: { tools, resources, prompts } } |
| HTTP | /health |
No | { name, status } — minimal, status code is the real signal (200 / 503) |
| HTTP | /health/detail |
Yes | Full ServerHealth (sessions, gateway topology) |
| HTTP | /info |
Yes | Same shape as the info MCP tool |
| HTTP | /dashboard |
Yes | Rendered HTML overview |
Why two health tiers? The public /health exists for infrastructure probes (Docker HEALTHCHECK, k8s liveness/readiness, load balancers) — they only need a status code. Operational details (session counts, gateway URLs) are reconnaissance signals and live behind protected: true.
Set these env vars at deploy time (e.g. in your Dockerfile or CI) so info reflects the actual build:
SOMAMCP_BUILD_COMMIT=abc123
SOMAMCP_BUILD_DATE=2026-05-22T00:00:00Z
SOMAMCP_BUILD_BRANCH=main
SOMAMCP_ENVIRONMENT=productionOr pass them programmatically (override wins over env):
createServer({
name: "my-server",
version: "1.0.0",
build: {
commit: process.env.GIT_SHA,
date: process.env.BUILD_DATE,
environment: "production",
},
})createServer({
name: "my-server",
version: "1.0.0",
enableIntrospection: false, // remove the `info` MCP tool
enableHealthEndpoint: false, // remove /health and /health/detail
enableInfoEndpoint: false, // remove /info
enableDashboard: false, // remove /dashboard
healthPath: "/healthz", // custom paths
healthDetailPath: "/health/full",
infoPath: "/about",
introspectionPrefix: "soma_", // → `soma_info` tool name
})Any artifact can opt into auth with protected: true. The route runs the server's authenticate callback via Hono middleware — same auth model as MCP protocol calls. Rejecting or throwing with a Response serves that response as-is, as on the MCP endpoint. Any other rejection or throw, or resolving to undefined/null, returns 401. If protected: true is set but no authenticate is configured, the route returns 401 unconditionally.
import { createServer, getRequestHeader } from "somamcp/node"
createServer({
name: "my-server",
version: "1.0.0",
// `authenticate` receives the web Request, for MCP calls and for protected
// routes alike. On stdio there is no request, and it receives `undefined`.
authenticate: async (req) => {
const header = getRequestHeader(req, "authorization")
const token = header?.replace(/^Bearer /, "")
if (token !== process.env.OPS_TOKEN) throw new Error("denied")
return { user: "ops" }
},
artifacts: [
{
type: "dynamic",
path: "/admin/stats",
protected: true,
handler: (c) => c.json({ secret: "stuff" }),
},
],
})For write endpoints, or anything the GET-only artifact shape doesn't cover, use addRoute. Same authenticate gate, method-aware, with optional onUnauthorized for custom 401 responses. A Response that authenticate rejects with is still served as-is, ahead of onUnauthorized.
server.addRoute({
method: ["POST", "PUT"],
path: "/upload",
protected: true,
handler: async (c) => {
const bytes = (await c.req.arrayBuffer()).byteLength
return c.json({ bytes, status: "accepted" })
},
onUnauthorized: (c) =>
c.json({ error: "unauthorized", hint: "provide Bearer" }, 401, { "WWW-Authenticate": "Bearer" }),
})Route ordering. Hono dispatches by registration order. addRoute registers immediately, alongside artifacts and introspection routes. Concrete non-overlapping paths compose safely in any order; for wildcards or overlapping prefixes, register earlier to take precedence.
See examples/protected-upload-server for a runnable end-to-end wiring: httpStream + authenticate + addRoute + a tool returning a content-array (text + inline image).
An auth provider is authentication that brings its own HTTP surface, such as an OAuth server. Pass it as auth:
const server = createServer({ auth: provider, name: "my-server", version: "1.0.0" })A provider (AuthProvider) has three parts:
authenticate(request)resolves the session that tools see ascontext.session, orundefinedwhen the request has no valid credentials. Protected artifacts and routes use it too. An explicitauthenticateoption takes precedence, as in FastMCP, while the provider's routes and challenge still apply.challenge({ endpoint, error, request, requestId })builds the response to an MCP request that failed authentication. This is typically a 401 with aWWW-Authenticateheader.requestIdis the request's JSON-RPCid, ornullfor aGET, a batch, or an unreadable body.erroris whatauthenticatethrew, and it is absent whenauthenticateresolved to no session. Only the MCP endpoint useschallenge: protected artifacts and routes keep their ownonUnauthorized, or 401. Without achallenge, the endpoint answers a plain 401.routes(endpoint)returns unprotected routes, such as OAuth metadata and/oauth/*endpoints. They are mounted once, when the server is created, so a route's path must not embed the MCP endpoint, whichstart({ httpStream: { endpoint } })can move later. To serve a path under the endpoint, such as/.well-known/oauth-protected-resource/mcp, mount a wildcard (/.well-known/oauth-protected-resource/*) and comparec.req.pathwithendpoint(), which reads the current path.
A tool's canAccess decides, per session, whether a caller sees and can call it. requireAuth and requireScopes, from the main entry, cover the usual checks under the names FastMCP gave them:
import { requireAuth, requireScopes } from "somamcp"
server.addTool({ canAccess: requireAuth, name: "me" /* … */ })
server.addTool({ canAccess: requireScopes("Mail.Send"), name: "send-mail" /* … */ })requireScopes needs every scope it names in session.scopes, an array or a Set. With the OAuth providers below, those are the scopes Microsoft granted.
canAccess hides a tool from a session that fails it, so a user with an older grant never learns the tool exists. requiredScopes keeps it listed, and asks for the scope when it's called (step-up):
server.addTool({ name: "send-mail", requiredScopes: ["Mail.Send"] /* … */ })A signed-in session without them gets a 403 with WWW-Authenticate: Bearer error="insufficient_scope", scope="…", instead of the tool running. scope holds what the session has as well as what's missing, so signing in again keeps both. The MCP SDK's client answers it by sending the user through sign-in with those scopes. Other clients may just show the error; a client that ignores it can't call the tool until its user reconnects. On stdio, a session without them gets a tool error. A server with no authenticate has no session, so nothing is checked.
Write each scope exactly as it appears in the OAuth server's scopes and in what the provider reports in session.scopes. The comparison is case-sensitive. A scope not on scopes can never be granted, because a sign-in is capped at that list, and the server logs an error when a tool requires one. A scope the provider reports in another spelling never matches, so a user is asked to sign in again every time. Check session.scopes once before you rely on it. A refused call doesn't reach the tool, so telemetry records no tool.error for it.
createAzureProvider makes the server its own OAuth 2.1 authorization server in front of Microsoft Entra ID. It handles dynamic client registration (RFC 7591), PKCE (RFC 7636), a consent page and token swap. Clients get the server's own JWTs, while Microsoft's tokens stay in encrypted storage, and tools see Microsoft's access token as context.session.accessToken.
import { createAzureProvider, createDiskStore, createServer } from "somamcp/node"
const auth = createAzureProvider({
allowedRedirectUriPatterns: ["https://claude.ai/*", "http://localhost:*/*"],
baseUrl: "https://mcp.example.com",
clientId: process.env.AZURE_CLIENT_ID!,
clientSecret: process.env.AZURE_CLIENT_SECRET!,
encryptionKey: process.env.TOKEN_ENCRYPTION_KEY!,
jwtSigningKey: process.env.JWT_SIGNING_KEY!,
scopes: ["openid", "profile", "offline_access", "User.Read"],
tenantId: process.env.AZURE_TENANT_ID!, // the tenant's id, a GUID
tokenStorage: createDiskStore({ directory: "/var/lib/mcp/tokens" }),
})
const server = createServer({ auth, name: "graph", version: "1.0.0" })
server.addTool({
execute: (_args, { session }) => callGraph(session?.accessToken),
name: "me",
parameters: z.object({}),
})
await server.start({ httpStream: { host: "0.0.0.0", port: 3000 }, transportType: "httpStream" })Use the tenant's GUID and openid. With both, Microsoft sends an id token, the session knows who signed in, and accounts from other tenants are refused. With common or without openid, any account Entra ID lets sign in to the app gets a session, and nothing says whose it is. The server warns at startup when openid is missing.
Who signed in. Tools get the user from the sign-in, never from a tool argument:
session.claimsholds the id token's claims, or{}when Microsoft sent no id token or one that can't be read.- The Azure provider's session (
AzureSession) addsoid(the user's object id),tid(their tenant) andupn(their sign-in name, frompreferred_username). - Microsoft sends an id token only when the scopes include
openid. Without it, all of these are empty, and the server warns at startup. - The id token stays in the server's store, like Microsoft's other tokens. The token response to the client has no
id_token, so a client never holds one. - The id token comes straight from Microsoft's token endpoint over TLS, so its signature isn't checked. OpenID Connect Core §3.1.3.7 allows that, and somamcp does no JWKS fetch. The session's identity never comes from Microsoft's access token, which Microsoft says clients must treat as opaque.
Restricting the tenant. When tenantId is a tenant's id (a GUID), a sign-in whose id token names another tenant is refused. Both tid and the issuer must match, and the client gets access_denied on its redirect URI. The server keeps openid whatever scope a client asks for, so Microsoft always sends an id token; a sign-in that still comes back without one is refused. Two settings skip the check:
- Server scopes without
openid: Microsoft never sends an id token, so there's nothing to check. The sign-in goes ahead, and the startup warning says the tenant isn't checked. - A domain name, or
common,organizationsorconsumers: there's no single tenant id to compare. Give the GUID to get the check.
acceptSignIn(claims) adds a rule of your own: it gets the id token's claims and returns the reason to refuse a sign-in, or undefined to accept it. On the Azure provider it runs after the tenant check, so it only sees accounts from your tenant.
Both run again on every refresh, on the newest id token. A rule tightened later, or a tenantId changed to a GUID, ends the sessions it now refuses: their next refresh gets invalid_grant, which makes the client sign in again. Access tokens already issued work until they expire, an hour by default. A session signed in without an id token, because openid was added later, has nothing to check. Its refreshes ask Microsoft only for what the sign-in granted, so no id token ever comes (unless widenScopesOnRefresh widens it for some other new scope, which brings one, and then the check runs and can end it), and it keeps refreshing, unchecked, for as long as it's in use. If those sessions must end, change jwtSigningKey, which signs everyone out.
provider.revokeUser(subject) ends every sign-in a user holds now. Their access tokens stop working at once, so their next call gets the 401, and their next refresh gets invalid_grant. They can sign in again straight away; to keep them out, add acceptSignIn as well. subject is the id token claim subjectClaim names: sub by default, and oid on the Azure provider, which tools read as context.session.oid. A sign-in made without that claim, such as one without openid, can't be matched. Microsoft's own tokens stay valid until they expire, because this server only stops using them. somamcp ships no admin endpoint. The safest way to call it is an operator's script, built with the server's tokenStorage (a createDiskStore or your own shared store) and encryptionKey, because every instance reads the same store:
const provider = createAzureProvider(sameConfigAsTheServer)
await provider.revokeUser(process.argv[2])
provider.close()Run it on a server host, or on a machine with a synced clock. The cutoff is that machine's time: if its clock runs behind the server's, a user who signed in or refreshed within the gap isn't revoked. If it runs ahead, the user's new sign-ins are refused until the gap passes. The call returns nothing either way, and a mistyped subject or the wrong encryptionKey does nothing without saying so, so check that the user's next call gets the 401.
If you expose it as a route, check an admin credential of your own. protected: true isn't enough, because it lets any signed-in user through.
createAzureProvider takes every option of the generic provider, such as claims, lifetimes and acceptSignIn, except upstream and store, which it fills in itself (tokenStorage is its name for the store).
For another upstream provider, createOAuthProxyProvider takes its endpoints under upstream (authorizationEndpoint, tokenEndpoint, clientId, clientSecret, name).
Routes:
/.well-known/oauth-authorization-server(RFC 8414)/.well-known/oauth-protected-resource, both bare and with the MCP endpoint appended (RFC 9728)POST /oauth/registerGET /oauth/authorize, which shows the consent pagePOST /oauth/consentGET /oauth/callback. Register<baseUrl>/oauth/callbackas the app's redirect URI in Entra ID.POST /oauth/token
An unauthenticated MCP request gets a 401 carrying WWW-Authenticate: Bearer resource_metadata="…", error="invalid_token", error_description="…". The description is Unauthorized: Authentication failed when there's no valid token. When authenticate throws, the client sees the message only of a UserError; anything else is logged and the 401 says Unauthorized: Authentication error, because an internal message can name files or store keys.
Errors. Inside the server, failures are a tagged union, OAuthError (InvalidGrant, UnknownClient, ProviderRejected and so on), returned as the Left of an Either. They become the standard OAuth codes (invalid_grant, invalid_client, …) only where a response leaves the server, because clients act on those codes. Until the client and its redirect URI are verified, an error is shown to the user, as JSON or as a page when the browser asks for HTML. After that, it goes back to the client on its redirect URI, so the app can tell the user what happened. That includes the user cancelling at Microsoft.
PKCE must use S256. allowPlainPkce: true also accepts plain, which OAuth 2.1 and the MCP spec drop; FastMCP allowed it by default.
baseUrl is the server's public origin, such as https://mcp.example.com. The OAuth routes mount at the root, so a baseUrl with a path, query or fragment throws when the provider is created. Serve the server at the root of its own host.
The consent page shows the app's registered name, the host the user returns to, the provider and the requested scopes. Anyone can register any name, so the page asks the user to approve only if they started from the return host, which is the verified part.
The page is a confirmation for the user, not a guard against a hostile client. Whoever starts a sign-in holds its transaction id, so they can approve it themselves. What stops a stolen sign-in is the redirect-URI allow-list: the code only ever goes to a URI on it. Keep allowedRedirectUriPatterns to hosts you trust, such as https://claude.ai/* and loopback.
Redirect-URI patterns are http(s)://host[:port][/path]. The scheme and host match literally, so no pattern can admit a host an attacker runs. * (any run) and ? (one character) match only in the path and query, and a pattern with no path allows any path on its origin. A * port and plain http are for loopback hosts only (localhost, 127.0.0.1, [::1]). createAzureProvider throws on any other pattern, such as https://claude.ai* or https://*. A client registered under a looser pattern can't use a URI the current patterns refuse.
The page has no scripts and can't be framed, and Deny comes first in the tab order. It has a light mode and works at phone width. A long scope list, such as the 20 or more a Microsoft 365 server asks for, shows its count and first 8 scopes, and the rest are one tap away under "Show all".
Moving from FastMCP. createAzureProvider takes FastMCP's AzureProviderConfig unchanged, so new AzureProvider(config) becomes createAzureProvider(config), and new DiskStore(options) becomes createDiskStore(options). The move is one way: somamcp reads everything FastMCP 4.22.10 stored and issued, so existing sign-ins survive it. It reads:
- the store layout and file names
- AES-256-GCM with the same scrypt-derived key
- FastMCP's HS256 JWTs
- the same record shapes and key prefixes
They survive only if the new server gets the same four values FastMCP had: baseUrl (the tokens' issuer and audience), jwtSigningKey, encryptionKey, and a tokenStorage on the same directory. A missing key falls back to a random one, as it does in FastMCP, which signs everyone out on the next restart.
Registered clients now expire 90 days after their last sign-in or refresh, and a day after registering if nobody signs in with them. A client FastMCP registered gets that expiry the next time it signs in or refreshes, so the store stops growing. A client unused that long gets invalid_client when it next tries to sign in, and some MCP clients then need the user to add the server again.
test/node/oauth-compat.test.ts guards this: it reads a store, tokens and HTTP captures that FastMCP generated (test/fixtures/fastmcp-4.22.10-oauth). xcheck.mjs in that directory also runs this server and FastMCP against a shared store. Its checks that FastMCP reads what somamcp writes are informational now, since nothing goes back to FastMCP.
Defaults:
- access tokens follow Microsoft's
expires_in - refresh tokens last 30 days
- codes last 5 minutes and sign-ins 10
- a new client lasts a day until its first sign-in completes, then 90 days after each sign-in or refresh
- the upstream timeout is 10 seconds
Set lifetimes to change them.
Open registration. Anyone can call /oauth/register without signing in, as MCP clients need. Two things stop that from filling the store:
- Unused clients lapse after a day. A client is kept for
lifetimes.unclaimedClient(a day) until its first sign-in completes, then forlifetimes.client(90 days). Claude and the MCP SDK clients register right before they sign in, so they're unaffected. A client that registers and comes back after the day getsinvalid_clientat/oauth/authorize, and the user has to remove the server and add it again. refuseRegistrationlets you rate-limit. It's called before the body is read, with the request's method, URL and headers but no body. Return aResponseto refuse, with your own status andRetry-After, or nothing to let it through. Behind a proxy, key it on the client IP the proxy forwards: somamcp can't tell which header to trust.
const auth = createAzureProvider({
// ...
refuseRegistration: (request) =>
limiter.allow(request.headers.get("cf-connecting-ip") ?? "unknown")
? undefined
: new Response(null, { headers: { "Retry-After": "60" }, status: 429 }),
})Behaviour to know about:
- Request bodies are capped at 64 KiB. A registration, consent or token request over that gets a 413. An MCP request that fails authentication is read up to 64 KiB for its JSON-RPC id; past that, the 401 has a
nullid. - PKCE is required. A request without a
code_challengeis sent back to the client withinvalid_request. - The token endpoint does not check
client_secret. PKCE binds a code to the client that started the flow. This matches FastMCP, so clients registered there keep working. - The client's
scopecan narrow the server'sscopes, never widen them. RFC 6749 §3.3 lets a server ignore part of what a client asks for. Scopes not on the list are dropped,openidandoffline_accessstay whenever the list has them, and a request with nothing on the list gets the whole list. A refresh is capped at what the sign-in was granted instead (RFC 6749 §6), and one with nothing granted on it sends no scope, so Microsoft keeps the original. The token response says what Microsoft granted. MCP clients ask forscopes_supported, which is the server's list, so they get what they ask for. - A scope added to
scopesreaches users already signed in only withwidenScopesOnRefresh: true. Without it, their refreshes keep what they were granted, and they get the new scope only by signing in again. With it, a refresh whose grant lacks a scope on the list (other thanopenidandoffline_access, which Microsoft often leaves out of what it reports) asks Microsoft for the whole list, and the grant becomes what Microsoft reports. If Microsoft refuses, as it does before anyone consents to the new scope (AADSTS65001), the server logs a warning and asks again for the old grant, so the refresh still works. That costs one extra token request, so the server remembers the refusal and doesn't widen that sign-in to the same list again for a day: a grant widens within a day of consent being given, or at once if the list changes again. Aserver_errorortemporarily_unavailablerefusal isn't remembered, and a refresh that fails to reach Microsoft isn't retried. A configured scope Microsoft never reports back, for example one spelled in another case, makes every refresh widen; when Microsoft grants it anyway, that costs nothing extra. Only the server widens: a refresh whose client names a scope is held to its grant as before, and a user who narrowedscopeat sign-in gets the whole list. Off by default. - Each token says what it is. Issued tokens carry
token_use(accessorrefresh), and each is refused in the other's place, as RFC 8725 §3.12 requires of an issuer of several kinds of JWT. FastMCP's tokens carry none, so they're accepted in either place until the client's first refresh replaces them. That's at most 30 days when FastMCP issued a refresh token, as it does withoffline_access. - A sign-in must pass the consent page. A callback for a request that was never approved is refused. This is defence in depth: the real protection is the random transaction id and the redirect-URI allow-list, because nothing ties the consent POST to the browser that showed the page.
- Issued JWTs carry no claims from Microsoft by default. Tools get the user from
session, and clients treat the token as opaque. FastMCP copied every simple claim, which put each user's name, sign-in name and IP address into bearer tokens. Setclaimsto copy some (true, or a policy withallow,blockandprefix). It reads the id token, and the access token unlessfromAccessToken: false; Microsoft says clients should treat that one as opaque.aud,client_id,exp,iat,iss,jti,nbf,scopeandtoken_useare never copied. - Without
jwtSigningKeyorencryptionKey, a random key is generated per process, so sign-ins and stored tokens do not survive a restart. The server warns at startup whenjwtSigningKeyis missing, and whenencryptionKeyis missing for a store you passed in. - A value that will not decrypt is logged, so a changed
encryptionKeyshows up in the logs instead of silently signing everyone out.
Not supported: client ID metadata documents, passthrough mode (handing clients the provider's own tokens), GitHub or Google presets, and JWKS verification.
A tool's execute may return a plain string or a full content-array with multimodal parts — telemetry passes the return value through unchanged. Use the exported imageContent / audioContent helpers to build parts without reaching into the backend. Both take { buffer } (any Uint8Array, including a Node Buffer) or { url } everywhere; the somamcp/node versions also take { path }. A URL's or path's extension picks the MIME type.
import { createServer, imageContent } from "somamcp/node"
server.addTool({
name: "hello_pixel",
description: "Text + inline image",
parameters: z.object({ name: z.string() }),
execute: async ({ name }) => ({
content: [{ type: "text", text: `hello, ${name}` }, await imageContent({ path: "./banner.png" })],
}),
})Telemetry is opt-in via the telemetry option. Every tool/resource/prompt call is automatically wrapped with timing, error classification, and optional input/output capture.
// createJsonFileTelemetry writes to disk, so it comes from somamcp/node.
import { createServer, createCompositeTelemetry, createConsoleTelemetry, createJsonFileTelemetry } from "somamcp/node"
const telemetry = createCompositeTelemetry([
createConsoleTelemetry(),
createJsonFileTelemetry({ filePath: "./logs/events.ndjson" }),
])
const server = createServer({
name: "my-server",
version: "1.0.0",
telemetry,
})server.addTool({
name: "processPayment",
description: "Process a payment",
parameters: z.object({ amount: z.number(), cardToken: z.string() }),
execute: async (args) => {
/* ... */
},
captureConfig: {
captureLevel: "full",
redactInputFields: ["cardToken"],
maxOutputSize: 2000,
},
})Capture levels:
"full"— input + output + metadata (default)"metadata"— timing + name + ids only"none"— no telemetry, and no error enrichment: a thrown error reaches the client as its bare message, withouterrorCategoryorsuggestions(see below)
A client can send W3C Trace Context in a request's _meta. somamcp checks it and hands it to the tool as context.trace, puts it on the tool's telemetry events, and forwards it on gateway calls. An invalid traceparent is dropped, and the call goes on. None of this needs a tracing library.
To record spans, add the optional peer dependency and pass a tracer:
pnpm add @opentelemetry/apiimport { createServer } from "somamcp"
import { createOtelTracer } from "somamcp/otel"
const server = createServer({
name: "my-server",
version: "1.0.0",
tracer: createOtelTracer(),
})Set up the OpenTelemetry SDK and its exporter the usual way. createOtelTracer uses the global provider's tracer, or the one you pass as { tracer }. With no SDK it records nothing and still passes context.trace along.
Each tool call gets one SERVER span named tools/call <tool>, following OpenTelemetry's semantic conventions for MCP, whose status is still Development:
- Parent: the client's
_metatrace context. The span that is current on the server, such as an HTTP span, becomes a link. With nothing in_meta, that current span is the parent. - Attributes:
mcp.method.name,gen_ai.tool.name,gen_ai.operation.name,jsonrpc.request.id, andmcp.session.idwhen there is one. - Errors: a tool's failure, including invalid arguments, sets
error.typetotool_errorand the status toERROR. A call naming a tool that doesn't exist, or one hidden from this caller, isn't an error: the span is named justtools/call, without the name the client sent, andrpc.status_codeis-32602, with noerror.typeor error status. - Privacy: spans hold no arguments, results or tool error messages.
Inside a span, context.trace is that span's context, so gateways nest under it. On Node with a context manager, which the OpenTelemetry Node SDK sets up, a span a tool opens nests by itself. On Workers without nodejs_compat there is no context manager, so pass the parent yourself:
import { otelContextFrom } from "somamcp/otel"
server.addTool({
name: "lookup",
execute: async (_args, context) => {
const span = tracer.startSpan("query", {}, otelContextFrom(context.trace))
// ...
span.end()
return "done"
},
})Limits: only tool calls get spans, not resources or prompts. The recommended attributes mcp.protocol.version and network.transport aren't set. A call refused with a 401 or 403 gets none. Gateway calls don't open a CLIENT span, so a remote server's span sits directly under the tool's. baggage isn't read or forwarded, because it can hold user data that a remote server shouldn't get by default. To plug in another tracing library, implement ToolTracer.
Errors thrown from tools are classified and returned as structured ContentResult responses with isError: true, with suggestions where they help the calling model correct itself.
// Thrown: new Error("Request timed out after 30s")
// Returned to the model:
{
isError: true,
content: [{
type: "text",
text: JSON.stringify({
errorCategory: "timeout",
message: "Request timed out after 30s",
relatedState: { toolName: "search" },
suggestions: ["The operation timed out. Try again or reduce the scope of the request"],
}),
}],
}How the category is chosen:
- A
UserErroris labelled as it says, subclasses included.new UserError(message, { category, suggestions })sets both. With nocategoryit'sexecution: the tool ran, and what it ran failed. That category has no generic suggestion, so the model reads the message as it is. Its words are never guessed from, because a tool that passes on a remote command's output (bash: chezmoi: command not found) didn't write them. - A schema library's error thrown inside
executeisvalidation, recognized by itsissuesarray (zod, valibot), not by its words. Arguments that fail the tool's ownparametersnever get this far: the server refuses them beforeexecuteruns, with the plainInvalid arguments for tool …message and no category. A tool that parses a remote response with zod should wrap the failure in aUserErrorwith its own category, or the caller is told to check the tool's parameter schema. - Anything else is guessed from its message, which is the library's own:
timeout,gateway,auth,not_foundorvalidationby keyword, andinternalotherwise.
suggestions replaces the category's generic ones, and suggestions: [] sends none. All of this needs the tool's telemetry wrapper, so a tool with captureLevel: "none" sends only the message.
throw new UserError(`No list named "${name}"`, { category: "not_found", suggestions: ["Call list-lists first"] })In 2.3 and earlier, a UserError with no category was labelled validation and came with "Check the tool's parameter schema and provide valid input".
Connect to remote MCP servers and proxy their tools as local tools.
import { createServer } from "somamcp"
import { createGatewayManager } from "somamcp/gateway"
const server = createServer({
name: "gateway-server",
version: "1.0.0",
gatewayManager: createGatewayManager,
gateways: [
{
id: "upstream",
url: "https://remote-mcp.example.com",
proxyTools: true, // register remote tools as local (prefixed: "upstream_toolname")
reconnect: true,
},
],
})Gateways live in somamcp/gateway. They use the MCP SDK client, which is about 54 KiB gzipped on a Worker, so the main entry doesn't load it: a server without gateways never bundles it. On the main entry, pass gatewayManager: createGatewayManager from somamcp/gateway whenever you set gateways; createServer throws without it. somamcp/node's createServer passes it for you, and somamcp/node also exports createGateway and createGatewayManager.
Gateways use the MCP SDK 2.x client. They speak the 2026-07-28 revision to servers that offer it, and fall back to the 2025 initialize handshake for the rest. A gateway's info.protocolVersion reports what was negotiated.
versionNegotiation:"auto"(the default) probes first withserver/discover. Some older servers answer that probe with a 5xx error, which fails the connection; set"legacy"for those to skip the probe.fetch: Replaces the globalfetchfor that gateway's requests. The client calls it as a plain function, so wrap a Workers service binding rather than passing its method:fetch: (url, init) => env.UPSTREAM.fetch(url, init).
Let agents file issues against your repo when they hit bugs or confusing behavior. The tool auto-redacts common credential patterns and PII, and includes a tool description that explicitly warns the LLM not to include proprietary data.
import { createServer, createFeedbackTool, createGithubFeedback } from "somamcp"
const server = createServer({ name: "my-mcp", version: "1.0.0" })
server.addTool(
createFeedbackTool({
provider: createGithubFeedback({
repo: "myorg/my-mcp",
getToken: () => process.env.GITHUB_FEEDBACK_TOKEN,
defaultLabels: ["agent-feedback"],
}),
// Auto-attached to each issue (visible in the issue body)
enrichment: async () => ({
server: server.getInfo(),
}),
extraLabels: ["from-agent"],
}),
)What gets redacted automatically (best-effort, not a substitute for caution):
- GitHub PATs (
ghp_*,github_pat_*) - AWS access keys (
AKIA*) - Stripe keys (
sk_live_*,pk_test_*, etc.) - Slack tokens (
xoxb-*,xoxp-*, etc.) - JWTs
- OpenAI/Anthropic API keys
- Bearer tokens (
Bearer <secret>) - Email addresses
- Private IPv4 addresses (RFC1918)
- Internal hostnames (
*.internal,*.local, etc.)
The tool response includes a redactionDetails summary so the agent knows what was scrubbed. Add custom patterns via redactionPatterns.
Providers:
createGithubFeedback({ repo, getToken, defaultLabels?, baseUrl? })— posts to GitHub IssuescreateWebhookFeedback({ url, headers?, transform? })— generic JSON POST to any endpoint (Linear, Jira, Sentry, custom relay)
Token security: the token only needs issues: write scope on the target repo. Use a GitHub App for fleet-scale (auditable, scoped, rotatable).
Mount HTTP routes on the embedded Hono app. A protected health dashboard is auto-mounted at /dashboard unless disabled.
const server = createServer({
name: "my-server",
version: "1.0.0",
enableDashboard: true, // default; requires `authenticate` to view
artifacts: [
{
type: "dynamic",
path: "/status",
handler: (c) => c.json({ ok: true }),
},
],
})
// With createServer from "somamcp/node":
await server.start({
transportType: "httpStream",
httpStream: { port: 8080 },
})| Import | Runs on | createServer defaults to |
Adds |
|---|---|---|---|
somamcp |
Workers, Deno, Bun, Node | createSdkBackend |
— |
somamcp/node |
Node (and Bun) | createNodeBackend |
start() on a port or stdio, createJsonFileTelemetry, { path } in the content helpers |
somamcp/backend |
anywhere | — | createSdkBackend and the backend types, for writing or wrapping a backend |
somamcp/otel |
anywhere | — | createOtelTracer and otelContextFrom. Needs the optional peer @opentelemetry/api. |
somamcp/gateway |
anywhere | — | createGatewayManager and createGateway, with the MCP client they need. See Gateways. |
somamcp/edge |
anywhere | createSdkBackend |
Nothing: an alias of somamcp kept through 2.x so 1.x imports resolve. Removed in 3.0. |
somamcp/node re-exports everything in somamcp and shares its modules rather than copying them, so values such as UserError are the same whichever entry you import them from. pnpm validate fails if Node-only code reaches anything somamcp loads, or if the core is emitted twice. It also runs the main entry inside workerd, Cloudflare's Workers runtime, without nodejs_compat, with both protocol eras, auth, content helpers, errors and resources (test/workers/).
On the main entry, a bare start() listens on nothing: it marks the server started and connects gateways. start() with a transport rejects with a pointer to somamcp/node. On somamcp/node, a bare start() serves stdio.
import { createServer } from "somamcp"
const server = createServer({
name: "my-worker",
version: "1.0.0",
// Workers has no process.env — pass build info from the fetch handler's `env`.
build: { commit: "abc123", environment: "production" },
})
export default { fetch: (request: Request) => server.fetch(request) }server.fetch serves both the MCP endpoint and every artifact/route you register, so /health, /info, and /dashboard work as they do on Node.
Types. The MCP SDK's own .d.mts files mention Buffer, so a Workers project without @types/node needs skipLibCheck: true (Wrangler's default). somamcp's own types do not.
Gateways need await server.start() to connect and register proxied tools. Workers forbids network I/O at module scope, so call it lazily inside your first request rather than at the top level. Without it, gateway tools are never registered.
Registering routes late. Hono builds its router on the first request and then rejects new routes ("matcher is already built"). Register every artifact and addRoute before serving traffic — on Workers that means at module scope, not inside the fetch handler.
Runtime reporting. getInfo().runtime is "edge" on Cloudflare Workers, Deno, and Vercel Edge, and "node" otherwise. Edge runtimes are detected positively — navigator.userAgent === "Cloudflare-Workers", or a Deno / EdgeRuntime global — rather than by the absence of process, because Workers with nodejs_compat supplies a working process.versions.node. On edge, arch / nodeVersion / platform report "unknown" or the user agent, rather than describing the compatibility shim. Bun deliberately reports "node": it is a Node-family server runtime with full Node APIs.
createSdkBackend (and createNodeBackend, the same backend with Node transports) builds on @modelcontextprotocol/server 2.x. One endpoint serves both protocol revisions:
2026-07-28, which current Claude clients request first.- 2025-era clients, which open with
initialize.
How it behaves:
- Stateless. Every request gets a fresh SDK server built from somamcp's registry. There are no sessions,
connect/disconnectevents never fire, and a 2025 client'sGETorDELETEis answered405.httpStream.stateless: falseis ignored, with a warning throughlogger. - Capabilities follow what's registered. Over HTTP, a server advertises
promptsonly once a prompt is registered,resourcesonce a resource or resource template is, andcompletionsonce a prompt or template is. Without them,prompts/list,resources/listand the rest answer method not found, as the spec expects, so a client doesn't spend a request per session listing nothing.toolsandloggingare always advertised: theinfotool is always there, and withoutloggingthe SDK dropscontext.loglines silently. Each request builds its server from the registry, so the server answers for something registered later on the next request. A client caches the capabilities it saw at connect, though, so one that connected before the first prompt or resource was registered must reconnect to list it. The same holds in reverse: once the last prompt is removed,prompts/listanswers method not found. On stdio, one server serves the whole connection, so it advertises every capability. authenticatereceives the webRequest, for MCP calls and for protected artifacts and routes. Read headers withgetRequestHeader. Rejecting or throwing with aResponseserves that response as-is, on the MCP endpoint and on protected artifacts and routes alike, so one wrong token gets one answer everywhere. Any other rejection or synchronous throw, or a nullish result, is a401: the auth provider'schallengeon the MCP endpoint, andonUnauthorized(routes) or a plain 401 on protected artifacts and routes. On stdio there is no request:authenticateis called once withundefined, and a failure serves without a session.canAccessis only ever called with a real session: with none, gated tools are hidden whenauthenticateis configured and shown otherwise.- Errors follow SDK 2.x and the current spec. Calling an unknown tool, or one hidden by
canAccess, is a JSON-RPCInvalidParamserror. Invalid arguments and thrown errors (includingUserError) areisErrortool results, so the model can read the message and retry. An invalid-arguments message names each bad argument by its path, as inInvalid arguments for tool 'get-tasks': listId: Invalid input: expected string, received undefined. - Schemas must describe themselves as JSON Schema (
~standard.jsonSchema): zod 4, ArkType, or Valibot via@valibot/to-json-schema. Other schemas still validate, but clients see an empty argument list;addToolwarns throughlogger. context.clientholds thenameandversionthe client reports about itself. A2026-07-28client sends them on every request, and a 2025 client on stdio sent them duringinitialize. A 2025 client over HTTP getsundefinedfor both: each request has a fresh server, and the client sends them only duringinitialize, an earlier request. A client can send any name, so use these for logs and metrics, never for authorization.context.logfollows the client's log level. A2026-07-28client receives tool logs only when its request asks for a log level (io.modelcontextprotocol/logLevel); otherwise the SDK drops them. 2025 clients receive them as before. Progress (reportProgress) is unaffected.streamKeepalive(enabled,intervalMs; default 20 s) writes SSE comment frames onto an in-flight call's own stream. With it on, every tool call is answered as an SSE stream, so a long call that produces no output still gets keepalives.httpStream.enableJsonResponseturns them off; it applies to2026-07-28exchanges only.maxRequestBodySize(bytes; default 4 MiB, the SDK's) caps an MCP request body. A larger one is answered413before it is parsed. Raise it for tools that take large inline arguments, such as a base64-encoded file. It applies tofetch()and to a port alike.httpStream.hostdefaults tolocalhost. Passhost: "0.0.0.0"to listen on every interface, for example in a container.- Health reports
runningfrom construction, because the backend can answerfetch()beforestart().stop()closes the listener and in-flight streams and reportsstopped(so/healthanswers 503), butfetch()still answers MCP requests. - Removal is real:
removeTool,removeResourceandremovePromptapply from the next request. - The MCP path comes first. The backend claims the MCP endpoint before artifacts and routes, so an
addRouteon that path is never reached. backendOptions(SdkBackendOptions) takesmcpPath, the endpoint forfetch()use (httpStream.endpointoverrides it), and, onsomamcp/node,stdioTransport, a transport to use in place of the process's stdin/stdout.
The MCP implementation is reached only through the BackendAdapter interface. createServer accepts a backend factory; each entry supplies its default. To wrap or replace the backend, implement BackendFactory:
import { createSdkBackend, type BackendFactory } from "somamcp/backend"
const myBackend: BackendFactory = (config, backendOptions) => {
const backend = createSdkBackend(config, backendOptions)
// ...wrap or extend it
return backend
}somamcp 2.0 drops FastMCP. If you need FastMCP, stay on somamcp ^1.5, which has both backends.
- Node servers import from
somamcp/node.start()withhttpStreamorstdionow needs it; onsomamcpit rejects. Changeimport { createServer } from "somamcp"to"somamcp/node". Everything elsesomamcpexports is re-exported there. - A bare
start()onsomamcpno longer serves stdio. It listens on nothing and resolves, so a stdio server that keeps importing fromsomamcpexits quietly. Onsomamcp/node, a barestart()still serves stdio. createJsonFileTelemetryand path-basedimageContent/audioContentmoved tosomamcp/node.{ buffer }and{ url }inputs still work fromsomamcp.somamcp/edgeis an alias ofsomamcp.createEdgeBackendandEdgeBackendOptionsare gone; the main entry runs on Workers itself.createFastMCPBackendis gone too.authenticatereceives the webRequesteverywhere, including protected routes on Node, where 1.x passedhttp.IncomingMessage. Its type is now(request: Request | undefined) => Promise<T>.getRequestHeaderreads both shapes, so code that uses it keeps working.- A nullish
authenticateresult now fails protected artifacts and routes with a 401, as it already did on the SDK backend's MCP endpoint. 1.x let it through on routes. addResourceTemplateis typed: it takes oneResourceTemplate<T>.- Removed options:
httpStream.eventStore,streamKeepalive.logLevel, and FastMCP'sbackendOptions(ping,health,roots,oauth). - Behavior from the SDK backend, if you were on FastMCP: stateless serving,
isErrorresults for invalid arguments,runninghealth from construction, and the rest of The SDK Backend. - Gateways use the SDK 2.x client; see Gateways.
Core
createServer(options)→SomaServerInstance- Types:
SomaServerOptions,SomaServerInstance,ServerHealth,ServerInfo,ServerCapabilities,CapabilitiesSummary,ToolOptions,ToolOptionsList
Primitives (somamcp-owned, no SDK types leak through)
Tool,Resource,Prompt,Context,Content,ContentResult,SessionAuth,UserError(andUserErrorOptions)
Build info
readBuildInfoFromEnv,resolveBuildInfo,getRuntimeInfo- Types:
BuildInfo,RuntimeInfo
Telemetry
createConsoleTelemetry,createCompositeTelemetry,createLogLayerTelemetry,NoopTelemetrycreateJsonFileTelemetry(somamcp/nodeonly)classifyError,createEnrichedError- Types:
TelemetryCollector,TelemetryEvent,CaptureLevel,ToolCaptureConfig,ErrorCategory
Gateway
createProxiedToolscreateGateway,createGatewayManager(somamcp/gatewayandsomamcp/nodeonly)- Types:
GatewayConfig,GatewayInstance,GatewayManagerFactory,GatewayManagerInstance,GatewayStatus
Artifacts
registerArtifacts,createDashboardArtifact,createHealthArtifact,createHealthDetailArtifact,createInfoArtifact- Types:
StaticArtifact,DynamicArtifact,DirectoryArtifact,ArtifactConfig,ArtifactAuthenticate
Auth & Routes
createAuthMiddleware,getRequestHeader,requireAuth,requireScopesauthonServerConfig: anAuthProvider(authenticate,challenge,routes); see Auth Providers- Types:
Authenticate,OnUnauthorized,AuthMiddlewareConfig,AuthProvider,AuthChallenge,AuthRoute,RouteConfig,RouteMethod
Transport
- Types:
TransportConfig,HttpStreamConfig(port,host,endpoint,cors,enableJsonResponse,stateless,sslCert/sslKey/sslCa); listening needssomamcp/node streamKeepaliveonServerConfig—{ enabled, intervalMs }; see The SDK BackendmaxRequestBodySizeonServerConfig— bytes, default 4 MiB; see The SDK Backend
Introspection
createInfoTool(auto-registered asinfo)createHealthTool,createCapabilitiesTool,createConnectionsTool(legacy, exported for manual use)
Feedback
createFeedbackTool,createGithubFeedback,createWebhookFeedbackredact,DEFAULT_REDACTION_PATTERNS- Types:
FeedbackProvider,FeedbackToolOptions,GithubFeedbackOptions,WebhookFeedbackOptions,RedactionPattern,RedactionResult,NormalizedFeedback,FeedbackSubmitResult
OAuth server (somamcp/node)
createAzureProvider,createOAuthProxyProvider- Stores:
createDiskStore,createMemoryStore,createEncryptedStore - Types:
AzureProviderConfig,AzureSession,OAuthAuthProvider(addsupstreamTokens(bearer)andclose()),OAuthSession,OAuthProxyConfig,UpstreamConfig,Lifetimes,ClaimsPolicy,OAuthError,TokenStore,DiskStoreOptions,UpstreamTokens
Content helpers
imageContent,audioContent({ buffer }or{ url };somamcp/nodeadds{ path })- Types:
ContentInput,NodeContentInput(somamcp/node)
Backend (somamcp and somamcp/backend)
createSdkBackend;createNodeBackend(somamcp/nodeonly)- Types:
BackendAdapter,BackendFactory,BackendSession,SdkBackendOptions
pnpm validate # Pre-commit: format + lint + typecheck + test + build
pnpm run ci # validate's checks without fixing, as CI runs them (type `run`: `pnpm ci` is a clean install)
pnpm test # Run tests
pnpm build # Build via tsdown
pnpm dev # Watch mode
pnpm typecheck # Type check onlyMIT © Jordan Burke
A SapientsAI project · Maintained by Jordan Burke