Guide: Build an MCP server
Expose tools, resources, and prompts that an MCP client — Claude Desktop, the Vercel AI SDK, your own agent — can discover and call. It's the same decorator-on-a-class, schema-on-the-decorator shape as REST, so if you've read the REST guide this will feel familiar.
Package:
@agentback/mcp. Built on the official MCP TypeScript SDK v2 (@modelcontextprotocol/server). Working examples:examples/hello-mcp(stdio) andexamples/hello-hybrid(REST + MCP).
What MCP exposes
| Primitive | Decorator | An LLM uses it to… |
|---|---|---|
| Tool | @tool(name, {input, output}) |
do something (call a function with typed args). |
| Resource | @resource(uri, {...}) |
read context (a document/blob addressed by URI). |
| Prompt | @prompt(name, {...}) |
fetch a reusable prompt template. |
A class tagged @mcpServer() groups these; the MCPServer discovers them and
registers them with the SDK.
1. A tool class
import {z} from 'zod';
import {mcpServer, tool} from '@agentback/mcp';
const EchoIn = z.object({text: z.string().min(1)});
const AddIn = z.object({a: z.number().int(), b: z.number().int()});
const AddOut = z.object({sum: z.number().int()});
@mcpServer()
export class MathTools {
@tool('echo', {description: 'Echo back the text', input: EchoIn})
echo(input: z.infer<typeof EchoIn>) {
return {echoed: input.text};
}
@tool('add', {description: 'Add two integers', input: AddIn, output: AddOut})
add(input: z.infer<typeof AddIn>): z.infer<typeof AddOut> {
return {sum: input.a + input.b};
}
}
input is validated and typed via z.infer. Declaring output constrains the
return type at compile time, validates it at runtime, and hands the schema to
the MCP SDK so structured-content clients consume it directly. Omit output to
leave the return type free.
2. Resources and prompts
In this framework, resources and prompts are parameterless methods — the handler takes no input and returns a value the framework wraps into the MCP wire shape.
import {resource, prompt} from '@agentback/mcp';
@mcpServer()
export class Docs {
@resource('docs://motd', {
name: 'motd',
description: 'Message of the day',
mimeType: 'text/plain',
})
motd() {
return 'Welcome to the service.'; // → {contents: [{uri, mimeType, text}]}
}
@prompt('triage', {description: 'Triage a bug report'})
triage() {
return 'You are a triage assistant. Classify the report by severity…';
// → {messages: [{role: 'user', content: {type: 'text', text}}]}
}
}
A string return is sent as text; a non-string is JSON-stringified.
3. Run the server
Add MCPComponent (it binds servers.MCPServer), register your tool classes
with app.service(...), configure, start. The stdio transport is active by
default — exactly what Claude Desktop and most local MCP clients speak.
A tool class is a DI service.
@mcpServer()(built on@injectable) makes it an extension of theMCP_SERVERSextension point and defaults it to singleton scope. The server discovers it by that extension and resolves it through its binding, so constructor@injectis honored no matter how it was registered — see §4.
import {RestApplication} from '@agentback/rest';
import {MCPComponent} from '@agentback/mcp';
import {MathTools, Docs} from './tools.js';
const app = new RestApplication();
app.component(MCPComponent);
app.configure('servers.MCPServer').to({
name: 'my-mcp',
version: '1.0.0',
// transports: {stdio: true}, // default; set false in tests/hybrid HTTP apps
});
app.service(MathTools);
app.service(Docs);
await app.start(); // MCP server up, tools/resources/prompts registered
You can use a plain
Applicationinstead ofRestApplicationif you only want MCP and no HTTP.RestApplicationis convenient when you also want the inspector UI (which is served over HTTP).
Expose it over Streamable HTTP
stdio is great for a local child process, but to let remote MCP clients
(Claude, Cursor, agents) reach the same tools, expose the in-process server over
the MCP Streamable HTTP transport with
@agentback/mcp-http:
import {installMcpHttp} from '@agentback/mcp-http';
await installMcpHttp(app); // before app.start() — mounts POST/GET/DELETE /mcp
Each client session gets its own isolated server instance (keyed by the
Mcp-Session-Id header). A client connects with the SDK's
StreamableHTTPClientTransport:
import {
Client,
StreamableHTTPClientTransport,
} from '@modelcontextprotocol/client';
const client = new Client({name: 'my-client', version: '1.0.0'});
await client.connect(
new StreamableHTTPClientTransport(new URL('http://host:port/mcp')),
);
await client.callTool({name: 'add', arguments: {a: 2, b: 40}});
This works alongside REST in one process (examples/hello-hybrid mounts /mcp,
/explorer, and /mcp-inspector together). To protect /mcp as an OAuth 2.1
resource server, pass installMcpHttp(app, {auth: {...}}) — see the
@agentback/mcp-http README.
Tag a tool with @tool('x', {scope: 'admin'}) to gate it by the caller's token
scopes.
How discovery works
@mcpServer() is built on @injectable: it tags the class as an extension of
the MCP_SERVERS extension point (extensionFor: MCP_SERVERS) and defaults it
to singleton scope. When you call app.service(MathTools), the framework reads
that metadata and tags the binding — you never call .tag(). At
app.start(), MCPServer discovers the MCP_SERVERS extensions, reflects over
their @tool/@resource/@prompt methods, and registers each with the SDK —
resolving the instance through its own binding, so constructor @inject works.
Protocol revision. Since 0.9.0 AgentBack serves
2026-07-28and the 2025 era from the same endpoint by default, on both stdio and HTTP — you get the current revision without asking, and existing clients keep working. Pin back withprotocol: 'legacy'oninstallMcpHttpor on theMCPServerconfig.Over HTTP the default is also stateless: no
Mcp-Session-Id, one server per request, soperSessionbinders run per request andeventStoreresumability does not apply. See the migration proposal.
diagram source (mermaid)
graph LR
D["@mcpServer() class"] -->|"app.service()"| B["binding [extensionFor: MCP_SERVERS]"]
B -->|"start(): extensionFilter"| M["MCPServer"]
M -->|reflect @tool/@resource/@prompt| SDK["@modelcontextprotocol/server"]
Consequence: adding a tool is adding a method (or a class + app.service).
Nothing central changes — the same composability as REST controllers.
4. Dependency injection in tools
Tools are DI-resolved classes, so inject services like anywhere else. With an
input schema, injects go at slot 1+ (slot 0 is the validated input); with no
input, slot 0 is free.
@mcpServer()
class WeatherTools {
constructor(@inject('services.WeatherApi') private api: WeatherApi) {}
@tool('forecast', {input: z.object({city: z.string()})})
async forecast(input: {city: string}) {
return this.api.lookup(input.city);
}
}
Register it with app.service(WeatherTools) — a tool is a service. The
dispatcher discovers it as an MCP_SERVERS extension and resolves the instance
through that binding, so this.api is injected. This holds for any
registration that carries the extension tag — app.service, app.controller,
or a manual bind().apply(extensionFor(MCP_SERVERS)). (A dual REST + MCP class —
@api and @mcpServer — still needs both restController for the routes
and service for the MCP extension, since restController tags it for REST
only.)
Ask the user mid-call (elicitation)
A tool can stop and ask the user something, then carry on with the answer.
Inject MCPBindings.ELICIT and call ask:
import {z} from 'zod';
import {inject} from '@agentback/core';
import {MCPBindings, mcpServer, tool, type Elicitor} from '@agentback/mcp';
const InspectIn = z.object({assembly: z.string()});
const InspectOut = z.object({part: z.string(), ok: z.boolean()});
// A FLAT z.object: string, number, integer, boolean and enum fields only.
const PartChoice = z.object({part: z.enum(['bolt', 'nut'])});
@mcpServer()
class Cad {
@tool('cad_inspect', {input: InspectIn, output: InspectOut})
async inspect(
input: z.infer<typeof InspectIn>,
@inject(MCPBindings.ELICIT) elicit: Elicitor, // slot 1: slot 0 is the input
): Promise<z.infer<typeof InspectOut>> {
const {part} = await elicit.ask('part', {
message: `Which part of ${input.assembly}?`,
standard: PartChoice,
});
return {part, ok: true}; // side effects go AFTER every ask
}
}
With no input: schema the elicitor goes at slot 0 instead
(async greet(@inject(MCPBindings.ELICIT) elicit: Elicitor)). Inject it as a
method parameter, never into a constructor: a tool class is a singleton,
so a constructor gets the app-level default, whose asks always fail.
examples/hello-mcp has a runnable greet tool.
- The tool re-runs from the top each round, on every protocol era. An
askwithout an answer yet suspends the call; the next round replays earlier answers, so the second run gets past the firstask. Ask before any side effect. Expensive work that must come before anask(an LLM call, a paid API, a slow search) goes inelicit.once(key, fn): the first round stores its JSON result in the request-state envelope and later rounds replay it, so it runs, and bills, once per call. Every round, the first included, gets the JSON form of the result (aDatecomes back an ISO string). The envelope is signed, not encrypted, so the client can read what you store: never pass a secret throughonce. Results are capped at 32 KiB per call. The envelope is not single-use either: a caller may replay a round's state on a new call with the same input within its hour, so keep freshness- or authorization-sensitive data out ofonce, or re-check it. askAll({a: formA, b: formB})asks several questions in one round.- A declined or cancelled answer throws
AgentErrorelicitation_declined(409); an answer that fails the form's schema isinvalid_input(400). - An optional
extendedform (raw JSON Schema) goes only to 2026-era clients declaring theopenai/elicitationextension. (On a 2025 connection OpenAI's forms use their ownopenai/elicitation/createmethod, which the SDK shim does not send, so those clients getstandard.) Its answer is still validated againststandard. TS SDK clients drop vendor keys on individual properties but keep top-level ones. - If your tool catches errors, let the suspend signal through:
if (isInputRequired(e)) throw e.
Who can be asked:
| Caller | What happens |
|---|---|
2026-07-28 client that declared elicitation |
input_required result; the client answers and retries |
2025 session (installMcpHttp(app, {protocol: 'legacy'})) or stdio, client declared elicitation |
the SDK sends elicitation/create over the connection and re-runs the tool |
a 2025 client on the default installMcpHttp mount (stateless), a client without elicitation, an in-process callTool |
AgentError elicitation_unavailable (422), naming the cause |
The default HTTP mount serves 2025-era clients statelessly, and a stateless
request has no connection to ask on. Use a 2026 client, stdio, or
protocol: 'legacy' if you must reach 2025 clients over HTTP. The MCP
Inspector answers too: it runs an asking tool through a real 2026-era client
and renders each question as a form. In tests, use an MCP client or
createTestApp (below).
State and deployment. Earlier answers ride in a requestState envelope
the client echoes back. It is signed, bound to the tool, the exact input and
the caller, and valid for an hour; it is not encrypted, so the client can
read the answers it already gave. It is signed with
MCPBindings.REQUEST_STATE_KEY, random per process by default: a
multi-instance deployment must share one key (bind it, or set
AGENTBACK_MCP_STATE_KEY), or a retry that lands on another instance is
refused and logged as a verification failure. A confirm: tool can also ask:
after the human confirms, the tool's question rounds carry a fresh single-use
confirmation that lasts as long as the envelope.
Cross-cutting. Each round is its own tools/call, so @authorize,
dispatch hooks and the price gate run every round, and the rate limiter debits
every round: a three-question tool costs four rate-limit units. Dispatch hooks
see info.inputRequired after next(); metering bills the call once, on its
final round. Tools that inject MCPBindings.ELICIT are left out of the agents
and CLI projections, which have no user to ask. Misuse fails loudly: swallowing
the suspend signal, asking after a streamed tool's first yield, the reserved
key confirm, a repeated key, or a non-flat form.
Testing. callTool cannot answer, so drive the tool through
createTestApp's in-memory client and answer from the test:
import {createTestApp} from '@agentback/testing';
it('asks which part', async () => {
await using t = await createTestApp(MyApp, {
mcpEra: 'modern',
mcpElicit: () => ({action: 'accept', content: {part: 'nut'}}),
});
const r = await t.mcp.callTool({
name: 'cad_inspect',
arguments: {assembly: 'hinge'},
});
expect(r.structuredContent).toEqual({part: 'nut', ok: true});
});
Answer {action: 'decline'} to test the elicitation_declined path.
This API is experimental (phase 2 of P1-7).
5. Inspect it: the MCP Inspector
A browser UI to list and exercise tools/resources/prompts without wiring up an MCP client:
import {installInspector} from '@agentback/mcp-inspector';
await installInspector(app); // before app.start(); needs servers.MCPServer bound
// -> UI at /mcp-inspector/, JSON API at /mcp-inspector/api/*
The inspector fills tool argument forms from each tool's Zod-derived JSON Schema,
shows validation errors inline, renders results, and logs a call history. When
a tool asks the user (elicit.ask, a 2026 confirm: prompt), it shows the
question as a form and continues the call with your answer. (It's
itself a worked example of a dogfooded REST controller — see its
README.)
Calling tools programmatically
MCPServer exposes the same dispatch path the SDK uses, handy for tests or
in-process use:
const mcp = await app.get<MCPServer>('servers.MCPServer');
await mcp.callTool('add', {a: 2, b: 40}); // → {sum: 42}
await mcp.readResource('motd'); // → {contents: [...]}
await mcp.getPrompt('triage'); // → {messages: [...]}
Invalid input throws with the structured Zod issues attached.
Testing an MCP server
examples/hello-mcp drives the server with a real
MCP client over stdio (transports: {stdio: true} and an in-memory client
pair). For unit-style checks, prefer callTool/readResource/getPrompt
against an app with transports: {stdio: false} so the server doesn't take over
the process's stdin. To test a tool that asks the user, use
createTestApp(App, {mcpEra: 'modern', mcpElicit: () => ({action: 'accept', content: {...}})})
from @agentback/testing: its in-memory client answers each question, so the
test sees the tool re-run with the answer.
Next
- Build a hybrid app — serve REST and MCP from one process, sharing the same schemas.
- Render a widget with MCP Apps — give a tool an
interactive
ui://widget a host renders inline for its result (SEP-1865). - Composition & extensibility — package your tools as a reusable component.