@cyanmycelium/mcp-core
Engine-neutral primitives for building Model Context Protocol servers and clients in TypeScript.
Power your agent
पब्लिशर की अपनी कमांड। PlugMCP एंडपॉइंट नहीं।
Host a copy with our keys and logs.
npx -y @cyanmycelium/[email protected]Claude Code में लोकल कमांड के लिए इंस्टॉल लिंक नहीं है। नीचे दी गई कमांड कॉपी करें और टर्मिनल में चलाएँ।
claude mcp add cyanmycelium-mcp-core -- npx -y @cyanmycelium/mcp-core@1.4.1टर्मिनल में चलाएँ।
{ "mcpServers": { "cyanmycelium-mcp-core": { "command": "npx", "args": [ "-y", "@cyanmycelium/[email protected]" ] } }}claude_desktop_config.json
रिमोट URL या आपकी मशीन पर कमांड? दोनों इंस्टॉल में क्या अंतर है
PlugMCP पर चलाएँ
A new server you create. It is not this listing's official endpoint. Use the publisher install when you want their URL and their credentials.
लॉन्चपब्लिशर से
Engine-neutral primitives for building Model Context Protocol servers and clients in TypeScript.
Engine-neutral Model Context Protocol primitives: behaviors, adapters, grammars, server, transports, client and LLM bridge.
Coding agent? Read AGENTS.md first: the whole integration on one page, with the failure modes that stay silent.
The official MCP TypeScript SDK gives you JSON-RPC plumbing and a way to register tools and resources. That is enough for a script that exposes a handful of functions. It is not enough when:
@cyanmycelium/mcp-core is the abstraction stack that makes those concerns first-class instead of bolt-ons. It is engine-neutral, runtime-agnostic, and has been used in production behind a multi-backend MCP server.
┌──────────────────────────────────────────────────────┐
│ GRAMMAR composable description overrides, │
│ resolved per session, mutable at runtime │
└──────────────────────────────────────────────────────┘
▲ applied to
┌──────────────────────────────────────────────────────┐
│ BEHAVIOR identity, namespace, tool/resource │
│ schemas (the MCP-side contract) │
└──────────────────────────────────────────────────────┘
▲ delegates runtime ops to
┌──────────────────────────────────────────────────────┐
│ ADAPTER runtime, executes against the actual │
│ host objects, emits change events │
└──────────────────────────────────────────────────────┘
▲ produces / consumes
┌──────────────────────────────────────────────────────┐
│ STATE serializable, read-only snapshots of │
│ those objects (resource contents) │
└──────────────────────────────────────────────────────┘
Each layer is independently testable. Each layer can be swapped without touching the others.
{tool, schema, handler} setupnpm install @cyanmycelium/mcp-core
Wiring a server to a real client is covered in HOWTO.md: stdio for the clients installed on a machine (Claude Desktop, Claude Code, Codex), HTTPS for the ones running on a vendor's servers (Claude.ai in a browser, ChatGPT on the web), and how to tell which case you are in.
Runs in both Node.js and the browser, and implements the two transports the MCP specification defines: stdio and Streamable HTTP, plus LoopbackTransport for a server and client sharing a process.
Roles matter here, because a transport means two opposite things depending on which end you are. A server launched as a subprocess speaks through its own stdin/stdout; the client that launched it speaks through the child's. Over HTTP, one side issues requests and the other terminates them.
Both standard transports, both roles.
Two readings that trip people up.
A Node MCP server needs nothing but this package. The broker is a relay, not a way to write a server. You reach for it when you have several servers to federate, credentials to centralise, or browsers to get out of, not to expose one server.
And the broker is a process you run (npx @cyanmycelium/mcp-broker), not a dependency you bundle. Your server stays on mcp-core and publishes itself into a slot; what you pay is an extra process, not extra code in your artifact.
The WebSocket tunnel to that broker is CyanMycelium topology rather than protocol, which is why it lives in mcp-broker-provider and not here: this package stays a faithful implementation of the specification and nothing else.
Revisions accepted during the handshake: 2025-11-25 (default), 2025-06-18, 2025-03-26, 2024-11-05. The server echoes the revision the client requested when it appears in that list, and answers with its newest otherwise; the client announces 2025-11-25 and disconnects if the server replies with a revision it cannot speak. Narrow the accepted set with withOptions({ protocolVersions: [...] }), or pin one revision by returning protocolVersion from your IMcpInitializer.
IMcpRequestContext contains the peer-provided JSON-RPC requestId, the MCP
method, optional params._meta, and a server-generated sequence. The
sequence is monotonic and unique for the lifetime of one McpServer, so an
adapter can correlate traces even when a peer reuses a JSON-RPC id after its
previous request has completed.
Every request a client may send is listed per revision in MCP_SERVER_REQUEST_METHODS, and tests/spec.coverage.test.ts sends each one to a server: a -32601 fails the build unless the method is declared in MCP_SERVER_UNSUPPORTED_METHODS with a reason (today only the experimental tasks/*). That test is what was missing when subscriptions, prompts, completion and logging all answered -32601 for five revisions.
Tool execution failures come back as isError: true results rather than JSON-RPC errors, which is what the spec asks for so the model can self-correct. Protocol errors stay protocol errors: an unknown tool is -32602, an unknown resource -32002, a JSON-RPC batch -32600 (batching was removed from MCP in 2025-06-18).
McpResourceContent is a union of a text and a binary variant, so reading one means narrowing on the field you need:
const content = await client.readResource("app://logo");
const bytes = content.text !== undefined ? Buffer.from(content.text) : Buffer.from(content.blob, "base64");
import { McpBehavior, McpAdapterBase, McpGrammar, McpToolResults } from "@cyanmycelium/mcp-core";
import { negotiateProtocolVersion, parseChallengeHeader } from "@cyanmycelium/mcp-core"; // protocol + auth primitives
import { McpServer, McpServerBuilder, LoopbackTransport } from "@cyanmycelium/mcp-core/server";
import { McpClient } from "@cyanmycelium/mcp-core/client";
import { LlmClient } from "@cyanmycelium/mcp-core/llm";
import { StdioTransport, ChildProcessTransport,
StreamableHttpTransport, StreamableHttpEndpoint } from "@cyanmycelium/mcp-core/node"; // Node-only
Tree-shaking ensures browser bundles never pull node:* modules.
The root entry point holds everything that depends on nothing: the behavior stack, protocol-version negotiation, and the OAuth pieces (metadata document, challenge building and parsing, canonical resource URI). They sit there rather than under /node because a browser client needs the same pieces in reverse: it parses the challenge a server builds.
A behavior owns the schemas, an adapter owns the execution. The server wires them together with a transport.
import {
McpAdapterBase,
McpBehavior,
McpBehaviorOptions,
McpResource,
McpResourceContent,
McpTool,
McpToolResult,
McpToolResults,
} from "@cyanmycelium/mcp-core";
import { McpServerBuilder } from "@cyanmycelium/mcp-core/server";
import { StdioTransport } from "@cyanmycelium/mcp-core/node";
// 1. State: read-only snapshot of the resource (here a single counter).
interface CounterState {
value: number;
}
// 2. Adapter: executes against the real object.
class CounterAdapter extends McpAdapterBase {
public static readonly URI = "app://counter";
private _value = 0;
constructor() {
super("app");
}
public async readResourceAsync(uri: string): Promise<McpResourceContent | undefined> {
if (uri !== CounterAdapter.URI) return undefined;
const state: CounterState = { value: this._value };
return { uri, mimeType: "application/json", text: JSON.stringify(state) };
}
public async executeToolAsync(
_uri: string,
toolName: string,
args: Record<string, unknown>,
): Promise<McpToolResult> {
switch (toolName) {
case "counter_increment":
this._value += (args.by as number | undefined) ?? 1;
this._forwardResourceContentChanged(CounterAdapter.URI);
return McpToolResults.json({ value: this._value });
case "counter_reset":
this._value = 0;
this._forwardResourceContentChanged(CounterAdapter.URI);
return McpToolResults.text("counter reset");
default:
return McpToolResults.error(`unknown tool: ${toolName}`);
}
}
}
// 3. Behavior: declares what the world sees. No execution code here.
class CounterBehavior extends McpBehavior {
public static readonly NAMESPACE = "counter";
constructor(adapter: CounterAdapter, options: McpBehaviorOptions = {}) {
super(adapter, { ...options, namespace: options.namespace ?? CounterBehavior.NAMESPACE });
}
protected override _buildResources(): McpResource[] {
return [{ uri: CounterAdapter.URI, name: "Counter", mimeType: "application/json" }];
}
protected override _buildTools(): McpTool[] {
return [
{
name: "counter_increment",
description: "Add `by` (default 1) to the counter and return its new value.",
inputSchema: {
type: "object",
properties: { by: { type: "number", description: "Increment amount." } },
additionalProperties: false,
},
},
{
name: "counter_reset",
description: "Reset the counter to zero.",
inputSchema: { type: "object", properties: {}, additionalProperties: false },
},
];
}
}
// 4. Server: wire transport + behaviors.
const adapter = new CounterAdapter();
const server = new McpServerBuilder()
.withName("counter-demo")
.withTransport(new StdioTransport())
.register(new CounterBehavior(adapter))
.build();
await server.start();
Save as server.ts, build, run with node server.js. Any MCP client (Claude Desktop, an SDK, a hand-rolled JSON-RPC over stdio) can now call counter_increment and counter_reset and read app://counter.
A grammar is a set of description overrides that the server applies on top of the behavior's baseline schemas before sending them to the client. The grammar layer is modular: multiple grammars can coexist in the same server and be selected per session by source (the calling client), by target (LLM provider, prompt dialect), or by locale.
As of 0.3.0, four layers stack with explicit precedence (low → high):
McpGrammar.merge(...layers) aggregates them in priority order: same-key entries in later layers win, missing entries cascade from earlier ones. The behavior is never required to know about static, store, or adapter layers: they merge transparently at the server.
What a grammar may override, per session:
title is the display name a client shows instead of the programmatic name, so it is the field to localise; name stays stable because clients and models address tools by it.
import { McpGrammar } from "@cyanmycelium/mcp-core";
const concise = McpGrammar.fromJSON({
counter_increment: {
description: "Add `by` to the counter.",
properties: { by: "How much to add." },
},
});
const verbose = McpGrammar.fromJSON({
counter_increment: {
description:
"Atomically increments the in-memory counter by the given amount " +
"and returns the new value. The previous value is not retained.",
},
});
const server = new McpServerBuilder()
.withName("counter-demo")
.withTransport(new StdioTransport())
.withGrammar("concise", concise)
.withGrammar("verbose", verbose)
.withGrammarResolver((clientInfo) =>
clientInfo.name.toLowerCase().includes("claude") ? "concise" : "verbose",
)
.register(new CounterBehavior(adapter))
.build();
Claude sees the short description, every other client sees the long one. No conditional code in the behavior.
Since 0.3.0, a behavior can ship its own grammars in code (one entry per <agent>:<locale>[@version] key it supports) without any external JSON files or broker layer. The application becomes autonomous on i18n; the broker is only needed if you want operator-editable overrides at runtime.
import { McpBehavior, McpGrammar } from "@cyanmycelium/mcp-core";
class CounterBehavior extends McpBehavior {
protected override _buildGrammars(): Map<string, McpGrammar> {
return new Map([
["default:en", McpGrammar.fromJSON({
tools: { counter_increment: {
description: "Add `by` (default 1) to the counter and return its new value.",
properties: { by: "Increment amount." },
}},
})],
["default:fr", McpGrammar.fromJSON({
tools: { counter_increment: {
description: "Ajoute `by` (1 par défaut) au compteur et retourne sa nouvelle valeur.",
properties: { by: "Quantité à ajouter." },
}},
})],
["claude:fr", McpGrammar.fromJSON({
tools: { counter_increment: {
description: "Incrément atomique du compteur. Renvoie la valeur post-mutation.",
}},
})],
]);
}
// _buildTools(), executeToolAsync(), etc.
}
withGrammarResolver policywithGrammarResolver accepts two forms. Pass a custom function for arbitrary logic, or a declarative GrammarResolverOptions to use the built-in <agent>:<locale>[@version] composer:
import { McpServerBuilder } from "@cyanmycelium/mcp-core";
// Declarative: locale + agent + (opt-in) version with progressive narrowing.
const server = new McpServerBuilder()
.withName("counter-demo")
.withTransport(new StdioTransport())
.register(new CounterBehavior(adapter))
.withGrammarResolver({
localeSource: (_, caps) => caps?.locale ?? process.env.LOCALE,
// versionFrom: (_, caps) => caps?.protocolVersion, // opt-in
})
.build();
For a Claude client requesting locale fr-CA, the resolver emits the chain ["claude:fr-ca", "claude:fr", "default:fr-ca", "default:fr", "claude:en", "default:en"]. The server tries each in order and picks the first key for which at least one of the four layers has registered a grammar: so the behavior's default:fr matches even when a more specific Canadian-French variant is not shipped.
The fallback narrowing order (["version", "locale-region", "locale", "agent"] by default) and key composition are both customizable; see GrammarResolverOptions for the full surface.
A grammar can carry the server's own words next to its tools': a server section with the one-line description (used for serverInfo.description when the initializer sets none) and the instructions a session receives (used when the initializer sets none). The initialize result also carries the key of the wording that was matched, in _meta.grammar, so a client can record which wording it was given.
{
"server": { "description": "A task's own files", "instructions": "Every path is relative to the task." },
"tools": { "list": { "title": "List", "description": "The files of a task.", "properties": { "taskId": "the task" } } },
"resources": { "ws://writes": { "name": "Writes", "description": "Every write." } }
}
With that, a behavior's code can declare structure only (tool names and schemas, resource URIs) and leave every word to grammar files. Two helpers make it a discipline rather than a habit:
loadGrammarDirectory(dir, { surface }) (@cyanmycelium/mcp-core/node) reads <dir>/<agent>/<locale>.json, composes each <agent>:<locale> grammar as the family's file laid over <dir>/default/<locale>.json, checks every file against the surface it describes (McpGrammar.check: a tool, a property, a resource the surface lacks is a problem, named with its file) and returns the grammars, the files with their sha256, and the problems. builder.withGrammars(loaded.grammars) registers them at once.builder.withWordingRule("default:en") checks at build() that every tool and every resource has a description in one place only: inline in the behavior, or in the named grammar, never both, never neither. A text can then not drift between two copies.A host has words that describe no tool: what a voice says about a task, what a page writes under a step. They belong to the same wording as the tools' words, in the same files, chosen by the same resolver. A grammar therefore carries a phrases section: keyed sentences with {holes} filled at use.
{
"server": { "description": "The factory's front" },
"tools": { "request": { "description": "Ask for what is missing." } },
"phrases": {
"step.fit": "Model fitted on {rows} rows, rmse {rmse}.",
"end.proposed": "Proposed to the station: {proposalId}."
}
}
grammar.phrase("step.fit", { rows: 19, rmse: 0.0008 }) fills the holes. A key the grammar lacks comes back as the key itself, so a missing sentence is seen where it should have been read; a hole with no value reads ?, never an invented value. fillPhrase and phraseHoles do the same on a bare template.merge overlays phrases like the rest (a family file rewords a sentence, never erases one); toJSON writes them back.reference.comparePhrases(other) lists the keys other lacks or adds and the phrases whose holes differ; loadGrammarDirectory(dir, { referenceLocale: "en" }) runs it for every file: a default/<locale> file must carry the reference locale's keys and holes, a family file may reword a subset. A locale that drifts is a named problem, like a tool the surface lacks. check({ phrases: [...keys the host reads] }) refuses a phrase under a key nobody reads.initialize has resolved the session's wording, resources/list includes grammar://phrases (when that wording carries phrases) and resources/read on it returns { "grammar": "<key>", "phrases": { ... } }. A page or a voice reads them through its own MCP session, in the language it announced, and fills them with McpGrammar.fromJSON({ phrases }).phrase(key, values); no second loader, no file served on the side.McpGrammarBehavior exposes the grammar store as a regular MCP behavior with six tools (grammar_list, grammar_read, grammar_set, grammar_delete, grammar_import, grammar_export). The agent can rewrite its own tool descriptions during a session, and the server emits notifications/tools/list_changed so clients re-fetch the updated schemas.
import { McpGrammarBehavior, McpGrammarStore } from "@cyanmycelium/mcp-core";
const store = new McpGrammarStore();
const server = new McpServerBuilder()
.withName("counter-demo")
.withTransport(new StdioTransport())
.withGrammarStore(store)
.register(new CounterBehavior(adapter), new McpGrammarBehavior(store))
.build();
Persist store.toJSON() to disk between runs to keep agent-authored descriptions across restarts.
The adapter declares which tools apply to which resource types. The behavior filters tools accordingly before advertising them.
import { ToolSupport } from "@cyanmycelium/mcp-core";
class CameraAdapter extends McpAdapterBase {
public override getToolSupport(
toolName: string,
resourceType?: string,
): ToolSupport | undefined {
if (toolName === "camera_orbit" && resourceType === "fixed-camera") {
return ToolSupport.None; // hidden from tools/list for fixed cameras
}
if (toolName === "camera_follow_path" && resourceType === "fps-camera") {
return ToolSupport.Partial; // visible, but with caveats in description
}
return undefined; // Full (default)
}
}
The client never sees tools it cannot actually call. No error spam.
Resource subscriptions. The server advertises resources: { subscribe: true, listChanged: true } as soon as a behavior exposes a resource or a template, and answers resources/subscribe / resources/unsubscribe itself: it keeps the set of URIs the session subscribed to, matched exactly, and forgets it on disconnect. Subscribing to a URI nothing can read is -32002; unsubscribing is always a success.
A behavior never sends a notification; it reports a change, and the server decides who hears it. With an adapter, that is the event it has always had:
class GaugeAdapter extends McpAdapterBase {
set(value: number): void {
this._value = value;
this._forwardResourceContentChanged("plant://gauge"); // notifications/resources/updated, to a subscribed session only
}
reshape(): void {
this._forwardResourceChanged(); // re-index + notifications/resources/list_changed
}
}
McpBehavior forwards both as onResourceUpdated / onResourcesListChanged, and drops its cached copy of the changed content first, so the read that follows is fresh. Before 1.3.0 the adapter raised these events and nothing listened. A behavior written from scratch implements the same two optional event sources, plus onPromptsChanged. Content the server serves without a behavior can be announced with server.notifyResourceUpdated(uri), which returns whether anything was sent.
On the client: client.onResourceUpdated.subscribe(uri => ...), then await client.subscribeResource(uri).
Prompts. A behavior contributes getPrompts() and getPromptAsync(name, args); the server advertises prompts only when one of them has some. Unknown names, missing required arguments and non-string argument values are -32602.
Completion. A behavior with completeAsync(ref, argument, context) makes the server advertise completions. A ref/prompt goes to the behavior listing that prompt, a ref/resource to the one declaring that uriTemplate; answers are capped at 100 values with total and hasMore set.
Logging. Off by default, since a server that advertises logging promises to emit it. With withOptions({ logging: true }) the server advertises it, answers logging/setLevel, and server.log(level, data, logger?) emits notifications/message at or above the level the client set (info until it sets one).
A custom IMcpServerHandlers written before 1.3.0 keeps working: the handlers for these methods are optional, and the server falls back to its own.
Declare templated resources so clients can discover the URI shape without enumerating every instance.
protected override _buildTemplate(): McpResourceTemplate[] {
return [{
uriTemplate: "app://camera/{cameraId}",
name: "Camera",
description: "Any camera in the active scene, by id.",
mimeType: "application/json",
}];
}
When a tool call arrives with a concrete URI (app://camera/main), the server matches it against templates if no exact static resource matches. The adapter receives the resolved URI and can parse the variables itself.
The behavior owns the schemas. The adapter owns the execution. Any adapter that satisfies the contract can be paired with the same behavior, so the same tool catalog runs against different backends without rewriting a single schema.
Reusing the CounterBehavior from the Quick start:
import { IMcpBehaviorAdapter } from "@cyanmycelium/mcp-core";
const behavior = (adapter: IMcpBehaviorAdapter) =>
new CounterBehavior(adapter, { namespace: "counter" });
// Same tools, different execution backends.
server.register(behavior(new InMemoryCounterAdapter())); // tests, demos
server.register(behavior(new RedisCounterAdapter(redis))); // production
server.register(behavior(new DbCounterAdapter(db))); // persisted
The pattern scales to richer domains: a single behavior describing mesh operations can run against a BabylonJS scene, a Cesium viewer, or an in-memory fixture, with the LLM-facing schemas never changing.
A server never opens its own connection: it is handed a transport, and withTransport() is required before build(). Framing, reconnection and authentication belong to whoever understands the medium.
Implement IMessageTransport for anything else (WebRTC, postMessage, gRPC). The WebSocket tunnel to a CyanMycelium broker lives in @cyanmycelium/mcp-broker-provider, which is where DirectTransport and MultiplexTransport moved in 0.5.0.
start() resolving does and does not meanawait server.start() resolves when the transport reports itself open. It is not a statement about the far end. Over stdio the two coincide, but over a tunnel (a broker slot, a relay, a reverse proxy) the socket is open long before the peer says whether it will serve this server at all, and a refusal arrives afterwards as an ordinary transport error. So do not print "connected" or "published" there; print it when the first initialize request arrives.
Two optional events carry what start() cannot:
const server = new McpServerBuilder().withName("my-app").withTransport(transport).build();
server.onTransportError?.subscribe((error) => console.warn("[my-app] transport:", error.message));
server.onDisconnected?.subscribe(() => console.warn("[my-app] transport closed, the next session renegotiates"));
await server.start();
When nothing is subscribed to onTransportError, the error is written to console.error rather than dropped: an unobserved transport failure is a bug, not a quiet success. Both members are optional on IMcpServer so existing implementations of the interface keep compiling; McpServer always provides them.
ChildProcessTransport is what lets an McpClient use the servers people actually publish, which ship as a command rather than a listening endpoint:
import { McpClient } from "@cyanmycelium/mcp-core/client";
import { ChildProcessTransport } from "@cyanmycelium/mcp-core/node";
const transport = new ChildProcessTransport({
command: "npx",
args: ["-y", "some-mcp-server"],
// stdio servers take their credentials from the environment: the spec
// reserves the OAuth flow for HTTP transports.
env: { API_TOKEN: process.env.API_TOKEN ?? "" },
stderr: (line) => console.warn(`[server] ${line}`),
});
const client = new McpClient({ name: "my-agent", version: "1.0.0" }, transport);
await client.connect();
close() follows the shutdown sequence the spec prescribes rather than killing outright: it closes the child's stdin so the server can finish on its own, sends SIGTERM if it lingers, then SIGKILL. Await transport.exited to know when the process is really gone.
A line on stderr means nothing is wrong: servers are explicitly allowed to log anything there, so it is routed to you and never mistaken for protocol.
StreamableHttpTransport connects an McpClient to a remote MCP endpoint:
import { McpClient } from "@cyanmycelium/mcp-core/client";
import { StreamableHttpTransport } from "@cyanmycelium/mcp-core/node";
const transport = new StreamableHttpTransport("https://example.com/mcp", {
// A function, not an object: read fresh per request, so rotating the token
// takes effect without rebuilding the transport and losing the session.
headers: () => ({ Authorization: `Bearer ${tokens.current}` }),
});
const client = new McpClient({ name: "my-agent", version: "1.0.0" }, transport);
await client.connect();
A plain object works too and is snapshotted at construction. OAuth itself is not implemented: the transport carries whatever credential you give it, and does not yet discover an authorization server or run a token flow.
StreamableHttpEndpoint is the other half: a request handler, not a server. It opens no socket, so listening, TLS and routing stay with your application while sessions, framing and the protocol's status codes stay with the package.
import { createServer } from "node:http";
import { McpServerBuilder } from "@cyanmycelium/mcp-core/server";
import { StreamableHttpEndpoint } from "@cyanmycelium/mcp-core/node";
const endpoint = new StreamableHttpEndpoint({
// One MCP server per session: a negotiated revision and a resolved grammar
// belong to one client. Behaviors are shared: they point at your state.
createServer: (transport) => new McpServerBuilder().withName("my-app").withTransport(transport).register(behavior).build(),
allowedOrigins: ["https://app.example.com"],
});
createServer((req, res) => void endpoint.handleRequest(req, res)).listen(3000);
Mount it the same way in Express or Fastify. A POST carrying a request is answered as application/json; notifications get 202; server-initiated messages travel on the standalone GET stream. Session ids are issued on the initialize response and required afterwards, DELETE terminates a session, and a request naming a terminated one gets 404 so the client knows to re-initialize.
Origin is validated and refused with 403 unless listed in allowedOrigins, which is closed by default: without that check any web page can drive a local MCP server through DNS rebinding. A request with no Origin header cannot come from a browser and is allowed.
The 403 body names the value that was refused and what it was compared against, because the mismatch is usually invisible from the outside (a scheme, a port, a trailing slash):
{
"error": "invalid_origin",
"error_description": "Origin \"http://app.example.com\" is not allowed: allowedOrigins holds \"https://app.example.com\". Origins are compared verbatim, so scheme, host, port and the absence of a trailing slash must all match."
}
Leaving allowedOrigins unset says so in its own words, since a closed door by design and a typo look identical from the client.
Pass auth and the endpoint becomes an OAuth 2.1 protected resource: it validates the bearer token, answers 401 and 403 with the RFC 9728 challenge, and hands the validated principal to your factory.
const endpoint = new StreamableHttpEndpoint({
createServer: (transport, sessionId, principal) => buildServerFor(transport, principal),
auth: {
resource: "https://mcp.example.com/mcp", // RFC 8707 canonical URI; tokens must name it
validator: myTokenValidator, // you verify the token, however you like
authorizationServers: ["https://auth.example.com"],
metadataUrl: "https://mcp.example.com/.well-known/oauth-protected-resource/mcp",
requiredScopes: ["mcp:call"],
},
});
// Serve the discovery document yourself, unauthenticated, since a client
// fetches it precisely because it has no token yet.
endpoint.protectedResourceMetadata();
MCP defines no token format and no authorization server, so neither does this package: ITokenValidator is the single seam, and verifying a JWT stays with your application. Everything above it (the metadata document, the challenge header and its parser, the canonical resource URI, the 401/403 semantics) lives in @cyanmycelium/mcp-core itself rather than under /node, because a client needs the same pieces in reverse and they depend on nothing.
The client hands the negotiated revision to the transport, which stamps MCP-Protocol-Version on every subsequent request. Session ids are captured and echoed automatically, the standalone GET stream is opened after initialization (with or without a session) and re-established with Last-Event-ID when the server closes it, honouring the SSE retry delay. A session terminated server-side (HTTP 404) surfaces as a transport close, since recovering means a fresh initialize; call client.connect() again to start a new session. close() sends an HTTP DELETE to release the session.
src/
index.ts everything isomorphic, re-exported
interfaces/ all shared contracts (one file per topic + barrel)
mcp.protocol.ts revisions supported + version negotiation
mcp.auth.ts OAuth resource-server primitives (metadata, challenge, RFC 8707 URI)
mcp.adapter.ts McpAdapterBase
mcp.behavior.ts McpBehavior (extends McpBehaviorBase)
mcp.behaviorBase.ts McpBehaviorBase, McpBehaviorOptions(Builder)
mcp.grammar.ts McpGrammar (layer + merge + fromJSON/toJSON)
mcp.grammarStore.ts McpGrammarStore (persistable, observable)
mcp.grammarBehavior.ts McpGrammarBehavior (store exposed as MCP behavior)
mcp.toolResult.ts McpToolResults.{text,json,resource,link,image,audio,error}
mcp.resolver.ts grammar key resolution from client identity
server/ McpServer, McpServerBuilder, JSON-RPC helpers, LoopbackTransport
client/ McpClient
llm/ LLM bridge interfaces and a generic client
node/ Node-only: StdioTransport, ChildProcessTransport,
StreamableHttpTransport, StreamableHttpEndpoint
The split is deliberate: anything that touches node:* lives under node/, everything else is isomorphic. That is why the OAuth and protocol primitives sit at the root while the HTTP wiring that uses them does not.
npm install
npm run build # tsup, bundles each entry point, emits .d.ts
npm run typecheck # tsc --noEmit, the only type gate: tsup transpiles without checking
npm test # vitest run
npm run lint
npm run lint:fix
npm run format:fix
Requires Node 20.11+.
typecheck is not redundant with build. tsup strips types rather than verifying them, and vitest does the same, so without it nothing would ever check the sources or the tests. It runs in CI between build and test.
Apache-2.0. See LICENSE.
Engine-neutral Model Context Protocol primitives: behaviors, adapters, grammars, server, transports, client and LLM bridge.
{ "mcpServers": { "cyanmycelium-mcp-core": { "command": "npx", "args": [ "-y", "@cyanmycelium/[email protected]" ] } }}टूल
अभी टूल सूची नहीं है। रिमोट सर्वर को पहले हेल्थ चेक के बाद सूची मिलती है।
FAQ
इस पेज पर Cursor, Claude Desktop, Claude Code या VS Code के लिए stdio कॉन्फ़िग कॉपी करें। यह पब्लिशर का इंस्टॉल इस्तेमाल करता है, PlugMCP प्रॉक्सी नहीं।
इस रिकॉर्ड में कोई ज़रूरी एनवायरनमेंट वेरिएबल दर्ज नहीं है।
@cyanmycelium/mcp Core stdio पर लोकल चलता है।
पिछली जाँच 2026-10-28 को हुई। Engine-neutral Model Context Protocol primitives: behaviors, adapters, grammars, server, transports, client and LLM bridge.