Functions become tools
Pass { add, greet } to createMcpApi. Object keys are tool names, so bundling and minification never rename a tool.
Register an object of functions. defuss-mcp publishes them to every Model Context Protocol client over stdio, Express, bunway or any Fetch handler. Agents read named schemas and repair rejected calls, and TypeScript callers get the original types back.
bun add defuss-mcpnpm install defuss-mcppnpm add defuss-mcpyarn add defuss-mcpimport { createMcpApi } from 'defuss-mcp';
import { createMcpHttp } from 'defuss-mcp/http';
const identity = { name: 'greeter', version: '1.0.0' };
const functions = { greet: (name: string) => 'Hello, ' + name };
export const api = createMcpApi(identity, functions, {
metadata: { greet: { annotations: { readOnlyHint: true } } },
});
const endpoint = createMcpHttp(api);
Bun.serve({ port: 3000, fetch: (req) => endpoint.fetch(req) });await tools.greet('Ada') "Hello, Ada" : string
Pass { add, greet } to createMcpApi. Object keys are tool names, so bundling and minification never rename a tool.
A generated contract turns the signature and JSDoc into named JSON Schema. A rejected argument returns its JSON Pointer and an instruction, not a stack trace.
Typed arrays travel as base64 trees, and Maps, BigInts, Dates and cycles use DSON. A plain JSON client still sees ordinary schemas.
stdio, Express, bunway and Fetch share one frozen catalog in JSON, SSE or automatic Streamable HTTP reply mode. Your application keeps its listener.
Authorization sees every HTTP exchange, and the defuss-rpc bridge re-enters the RPC dispatcher, so method guards also apply to MCP callers.
Titles and annotations such as readOnlyHint and destructiveHint reach tools/list, where hosts decide whether to ask before a call.
The registry freezes its catalog when the first transport starts. Each HTTP request gets its own SDK server with its own headers and cancellation signal, while every request shares the compiled schemas.
An object of functions, a tuple, or explicit .json, .dson and .binary tools with their own schemas.
bunx defuss-mcp reads exports and JSDoc and writes named schemas that agents can discover.
Hand the registry to createMcpHttp or serveMcpStdio. Your host keeps its routes, listener and authentication.
getMcpClient<typeof api> returns typed functions. Every other MCP client uses the advertised schemas.
This page imports the published build, registers four tools and connects the official MCP TypeScript client to endpoint.fetch. Every exchange below is real Streamable HTTP; it never leaves your browser.
The demo starts when it scrolls into view.
The catalog a stock MCP client receives. Pick a tool, edit its arguments as JSON and send tools/call.
byteAdd(a: Uint8Array, b: Uint8Array) carries a generated contract: two named base64 fields. The agent sends an invalid second operand. The tool error names the field and the fix, and the agent applies it on the same connection.
The typed facade negotiates the compact binary codec and falls back to DSON for rich graphs. A Uint8Array returns as a Uint8Array, and a Map as a Map.
const { tools } = await getMcpClient<typeof api>(sdk);
await tools.add(2, 3); // 5
await tools.byteAdd(Uint8Array.of(1, 2), Uint8Array.of(3, 4)); // Uint8Array [4, 6]
await tools.tally(['mcp', 'dson', 'mcp']); // Map { mcp => 2, dson => 1 }| # | JSON-RPC | Status | Reply | Bytes in, out | ms |
|---|
Before a release, make e2e installs the tarball into an empty project and starts real server processes. Each official client discovers a byte tool, repairs a rejected field and calls the guarded RPC bridge, in every reply mode. A missing or failed cell fails the build.
| Client | Node, Express | Bun, Express | Bun, bunway | Bun, Fetch | Node, stdio | Bun, stdio |
|---|---|---|---|---|---|---|
| TypeScript SDK on Node.js | 6 | 6 | 6 | 6 | 2 | 2 |
| TypeScript SDK on Bun | 6 | 6 | 6 | 6 | 2 | 2 |
| Python SDK | 6 | 6 | 6 | 6 | 2 | 2 |
| Go SDK | 3 | 3 | 3 | 3 | 1 | 1 |
| MCP Inspector CLI | 3 | 3 | 3 | 3 | 1 | 1 |
Measured with Node.js 24.22.3, Bun 1.4.5, Python 3.12.15 (MCP SDK 2.3.0), Go 1.27.4 (MCP SDK v1.8.0), MCP Inspector 2.16.0 and the TypeScript SDK 2.4.0 on Apple M5 Max, tarball sha256 1417c6d1d467.
Every figure comes from make bench for v0.6.0 on one Apple M5 Max with other work running (load average 7.5). Clients and servers run in separate processes over loopback.
Median of serial calls in milliseconds; shorter is faster. The MCP bar calls a registered function with a JSON reply, the RPC bar calls the same function through defuss-rpc on the same listener.
| Case | MCP function call | defuss-rpc call |
|---|---|---|
| Node, Express | 0.106 ms | 0.081 ms |
| Bun, Express | 0.103 ms | 0.067 ms |
| Bun, bunway | 0.072 ms | 0.051 ms |
| Bun, Fetch | 0.070 ms | 0.048 ms |
| Node, stdio | 0.033 ms | |
| Bun, stdio | 0.028 ms |
Payload MiB per second in both directions with eight calls in flight; longer is faster.
| Case | Payload MiB/s, eight in flight |
|---|---|
| Typed client, compact | 214 MiB/s |
| Binary tool, base64 | 130 MiB/s |
| Typed client, DSON | 27 MiB/s |
| defuss-rpc, DSON | 31 MiB/s |
Median milliseconds over eight alternating rounds against v0.4.0; shorter is faster. A Fetch host loads no Node adapter.
| Case | v0.6.0 | v0.4.0 |
|---|---|---|
| Node.js | 38.9 ms | 50.4 ms |
| Bun | 31.2 ms | 43.9 ms |
The raw samples, the full matrix and the paired release comparison ship in the release archive under validation/. The verification notes describe sampling and limits.
ESM, CommonJS and TypeScript declarations for Node.js 22.19 or newer and Bun. Five runtime dependencies: the official MCP server SDK and its Node adapter, Ajv with its formats, and defuss-dson.
A Fetch handler serves Streamable HTTP. The same endpoint works in any router that passes a Request.
// server.ts, run with: bun server.ts
import { createMcpApi } from 'defuss-mcp';
import { createMcpHttp } from 'defuss-mcp/http';
export const api = createMcpApi(
{ name: 'greeter', version: '1.0.0' },
{ greet(name: string) { return 'Hello, ' + name; } },
{ metadata: { greet: { title: 'Greet', annotations: { readOnlyHint: true } } } },
);
const endpoint = createMcpHttp(api);
Bun.serve({ hostname: '127.0.0.1', port: 3000, fetch: (request) => endpoint.fetch(request) });
// client.ts: the official SDK client with typed functions
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import { getMcpClient } from 'defuss-mcp/client';
import type { api } from './server.ts';
const sdk = new Client({ name: 'caller', version: '1.0.0' });
await sdk.connect(new StreamableHTTPClientTransport(new URL('http://127.0.0.1:3000/mcp')));
const { tools } = await getMcpClient<typeof api>(sdk);
console.log(await tools.greet('Ada')); // "Hello, Ada", typed as stringMount the endpoint on your route. authorize sees every exchange, including discovery; validation returns corrections instead of running the handler.
import express from 'express';
import { createMcpApi } from 'defuss-mcp';
import { createMcpHttp } from 'defuss-mcp/http';
import { ajvValidator } from 'defuss-mcp/validation';
const tools = createMcpApi({ name: 'arithmetic', version: '1.0.0' }, { compile: ajvValidator() });
tools.json<{ a: number; b: number }>('add', {
type: 'object',
properties: { a: { type: 'number' }, b: { type: 'number' } },
required: ['a', 'b'],
additionalProperties: false,
}, ({ a, b }) => a + b, { description: 'Add two numbers.', annotations: { readOnlyHint: true } });
const token = process.env.MCP_API_TOKEN;
if (!token) throw new Error('Set MCP_API_TOKEN before starting the server.');
const endpoint = createMcpHttp(tools, {
authorize: (request) => request.headers.get('authorization') === 'Bearer ' + token,
});
const app = express();
app.all('/mcp', endpoint.middleware);
app.listen(3000, '127.0.0.1');A desktop host launches the server as a child process and speaks MCP over its pipes. Keep stdout for the protocol and log to stderr.
import { createMcpApi } from 'defuss-mcp';
import { serveMcpStdio } from 'defuss-mcp/stdio';
const notes = ['Ship the release', 'Review the client matrix'];
const api = createMcpApi({ name: 'notes', version: '1.0.0' }, {
search(query: string, limit = 10) { return notes.filter((note) => note.includes(query)).slice(0, limit); },
});
api.observeCalls((event) => {
process.stderr.write(JSON.stringify({ time: new Date().toISOString(), level: 'info', ...event }) + '\n');
});
const handle = await serveMcpStdio(api);
process.once('SIGTERM', () => void handle.close());The contract generator reads exports, imported interfaces and JSDoc, and writes a binding module next to the source. --check fails CI on stale output.
bunx defuss-mcp --entry src/math.ts --out src/math.mcp.ts// math.ts
/** Add equal-length byte arrays elementwise, modulo 256. */
export function add(a: Uint8Array, b: Uint8Array): Uint8Array {
if (a.length !== b.length) throw new RangeError('Expected equal lengths.');
return a.map((value, i) => value + b[i]!);
}
// server.ts: a stock client now sees { a: base64, b: base64 } and gets corrections at /a or /b
import { createMcpApi } from 'defuss-mcp';
import { add } from './math.mcp.js';
export const api = createMcpApi({ name: 'math', version: '1' }, { add });Coding agents can read llms.txt: the API, the wire contracts and runnable examples in one plain-text file. Paste this prompt into your agent:
Read https://mcp.defuss.org/llms.txt. Expose the functions in src/tools.ts as MCP tools with defuss-mcp: use createMcpApi with readOnlyHint metadata for functions that do not write, mount createMcpHttp on our existing router, and add a test that calls each tool through the official MCP client.
The same registry answers the two newest MCP revisions: 2026-07-28, which clients find through server/discover, and 2025-11-25 with its initialize handshake. It serves them over stdio and Streamable HTTP, with JSON, SSE or automatic replies. With automatic negotiation, the official TypeScript client selects 2026-07-28.
| Import | Call | What it does |
|---|---|---|
defuss-mcp | createMcpApi(identity, functions, options) | Registers an object or tuple of functions; options set the schema compiler, the error sink and per-tool metadata. |
defuss-mcp | .json, .dson, .binary, .group | Adds tools with a hand-written schema, a DSON graph, base64 bytes, or a staged batch that publishes atomically. |
defuss-mcp | .observeCalls, .processCalls | Receives start and finish events with durations, or transforms decoded inputs and results. |
defuss-mcp/http | createMcpHttp(registry, options) | Returns fetch, middleware and close with host, origin, size and authorization checks. |
defuss-mcp/stdio | serveMcpStdio(registry, options?) | Serves the catalog on the process pipes of a child launched by the client. Reads stdin in linear time; maxMessageBytes bounds one message. |
defuss-mcp/client | getMcpClient<typeof api>(sdk) | Discovers the catalog once and returns typed remote functions over your connected SDK client. |
defuss-mcp/validation | ajvValidator() | Compiles JSON Schema 2020-12 and draft-07 with formats; failures become pointer-based corrections. |
defuss-mcp/rpc | exposeRpc(registry, rpcRoute, options) | Publishes defuss-rpc methods as Namespace.method tools and dispatches through the RPC route and its guards. |
Read the source, the architecture notes and the verification evidence, or hand llms.txt to your coding agent.
The link may be old. The home page has the demo, the client matrix and the install steps.