Skip to content

MCP

An app can serve the Model Context Protocol to AI agents (desktop agents, IDEs, hosted assistants) from its own server. An MCP endpoint is a route of the app; each MCP tool, MCP resource and MCP prompt it lists is a handler, so each keeps its input validation, its middleware, its errors and their masking. Hamur adds no dependency for it and uses Web APIs only, so it runs on every server preset.

It is experimental: the protocol still changes between revisions, and the key may change with it. The endpoint speaks MCP 2026-07-28 and also serves clients of 2025-11-25 on the same route.

Not the same thing as WebMCP, where a page registers tools in the browser. The experimental.* keys are listed in Experimental keys.

Turn it on

ts
import { defineConfig } from "hamur"

export default defineConfig({
  framework: "html",
  app: { origin: "https://blog.example.com" },
  experimental: { mcp: true },
})

experimental.mcp is false by default. Off, a handler with the mcp key fails the build with server/mcp.ts#mcp: the mcp key needs experimental.mcp: true, and a server without any mcp key carries none of the protocol's code.

Tools and the endpoint

A tool is a handler with a meta.description; its meta.summary is the tool's title. It needs no route and no export from server/index.ts. A tool no door exports runs its own middleware behind the endpoint's, and no door's handlerMiddleware: that list reaches only the handlers its door exports.

ts
import { defineHandler, notFound } from "hamur/server"
import { schema } from "./mcp-schema.ts"

const posts = [{ id: "1", title: "Hello", region: "eu" }]

const search = schema<{ query: string; region: string }>(
  {
    type: "object",
    properties: {
      query: { type: "string", description: "Words to look for" },
      region: { type: "string", "x-mcp-header": "Region" },
    },
    required: ["query", "region"],
  },
  (value) => {
    const { query, region } = (value ?? {}) as { query?: unknown; region?: unknown }
    if (typeof query !== "string") return { issues: [{ message: "Expected a string", path: ["query"] }] }
    if (typeof region !== "string") return { issues: [{ message: "Expected a string", path: ["region"] }] }
    return { value: { query, region } }
  },
)

export const searchPosts = defineHandler({
  method: "GET",
  meta: { summary: "Search posts", description: "Full-text search over the published posts of one region" },
  input: search,
  handler: ({ query, region }) => posts.filter((post) => post.region === region && post.title.includes(query)),
})

const byId = schema<{ id: string }>(
  { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
  (value) => {
    const { id } = (value ?? {}) as { id?: unknown }
    return typeof id === "string" ? { value: { id } } : { issues: [{ message: "Expected a string", path: ["id"] }] }
  },
)

export const deletePost = defineHandler({
  meta: { description: "Deletes one post" },
  input: byId,
  handler: ({ id }) => {
    const at = posts.findIndex((post) => post.id === id)
    if (at === -1) notFound()
    posts.splice(at, 1)
    return `Deleted post ${id}`
  },
})

export const getPost = defineHandler({
  meta: { summary: "Post", description: "One post as JSON" },
  input: byId,
  handler: ({ id }) => posts.find((post) => post.id === id) ?? notFound(),
})

export const reviewPost = defineHandler({
  meta: { description: "Ask for a review of a draft" },
  input: byId,
  handler: ({ id }) => "Review the post " + id + " for tone and facts.",
})

The endpoint is the mcp key of a handler with a route, exported from server/index.ts like any route. tools is an object literal: each key is the tool's name, each value a handler, or { handler, annotations }.

ts
import { createError, defineHandler, defineMiddleware, useRuntimeConfig } from "hamur/server"
import { deletePost, getPost, reviewPost, searchPosts } from "./mcp-posts.ts"

const requireToken = defineMiddleware(({ event, next }) => {
  const token = useRuntimeConfig(event).mcpToken as string | undefined
  if (!token || event.request.headers.get("authorization") !== `Bearer ${token}`) throw createError({ status: 401 })
  return next()
})

export const mcp = defineHandler({
  route: "/mcp",
  middleware: [requireToken],
  mcp: {
    instructions: "Tools for the blog's posts.",
    tools: { searchPosts, deletePost: { handler: deletePost, annotations: { destructiveHint: true } } },
    resources: { post: { uriTemplate: "posts://{id}", mimeType: "application/json", handler: getPost } },
    prompts: { review: reviewPost },
    resourceMetadata: { authorizationServers: ["https://auth.example.com"] },
  },
})

The sample's schema helper only stands in for a schema library; any library that implements Standard JSON Schema works, since the endpoint lists each tool's input schema from it.

ts
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "hamur/server"

type Check<T> = (value: unknown) => { value: T } | { issues: Array<{ message: string; path?: PropertyKey[] }> }

/** A schema with a validator and its JSON Schema; a library such as Zod or Valibot gives both. */
export function schema<T>(
  jsonSchema: Record<string, unknown>,
  check: Check<T>,
): StandardSchemaV1<unknown, T> & StandardJSONSchemaV1<unknown, T> {
  return {
    "~standard": {
      version: 1,
      vendor: "docs",
      validate: check,
      jsonSchema: { input: () => jsonSchema, output: () => jsonSchema },
    },
  } as StandardSchemaV1<unknown, T> & StandardJSONSchemaV1<unknown, T>
}
Key
toolsan object literal of handlers made with defineHandler, or { handler, annotations }. A name is 1 to 128 characters of A-Z, a-z, 0-9, _, - and .. The order written is the order tools/list gives
resourcesan object literal of { uri, mimeType?, handler } or { uriTemplate, mimeType?, handler }; the key is the resource's name. uri and uriTemplate are string literals
promptsan object literal of handlers whose input fields are strings; the key is the prompt's name
instructionsa string server/discover and initialize answer
resourceMetadata{ authorizationServers, scopesSupported? }, string array literals: see Protected-resource metadata

The handler with mcp answers POST only and takes no handler, input, output, raw, status, events, cache, prerender, batch, live, jsonRpc or websocket; its own middleware and timeout work as on any route. A client import of it fails with app/x.ts imports mcp from "#server", but it is an MCP endpoint: it answers a URL, not a call, and the OpenAPI document lists none.

What a tool lists

FieldFrom
namethe key in tools
titlemeta.summary
descriptionmeta.description
inputSchemathe input schema's JSON Schema ({ "type": "object" } without input)
outputSchemathe output schema's JSON Schema; for a 2025-11-25 client only when it is an object schema
annotationsannotations of { handler, annotations }, else from the handler's method: GET, HEAD and QUERY give { readOnlyHint: true }

Annotations are hints an agent reads. Hamur enforces nothing by them.

Errors at definition

Each is a TypeError when the endpoint's module loads; the build reports the ones it can read from the source first.

CaseMessage
no routemcp needs a route
a key that answersmcp cannot be used with handler, input, output, raw, status, events, cache, prerender, batch, live, jsonRpc or websocket: its tools answer
another methodmcp needs method "POST"
mcp or tools that is not an object literalserver/mcp.ts#mcp: mcp.tools must be an object literal; the build reads its names
a bad nameserver/mcp.ts#mcp: tool name "my tool" must be 1 to 128 characters of A-Z, a-z, 0-9, "_", "-", "."
a value that is not a handlermcp tool "searchPosts" must be a handler made with defineHandler
a handler with a route-shaped keymcp tool "searchPosts" cannot have route, raw, websocket, batch, live, jsonRpc or mcp
no descriptionmcp tool "searchPosts" needs meta.description
an input without a JSON Schemamcp tool "searchPosts": its input schema has no ~standard.jsonSchema; use a library that implements Standard JSON Schema
an input that is not an objectmcp tool "searchPosts": input must be an object schema (MCP tool arguments are an object)
a bad x-mcp-headermcp tool "runQuery": x-mcp-header "Region" at /properties/region is invalid: the name must be an HTTP token (or the name is used twice (names compare without case), the property must be a string, integer or boolean, it must be reached from the root through properties only)
a bad annotations keymcp tool "deletePost": annotations has no key "destructive"; it takes title, readOnlyHint, destructiveHint, idempotentHint, openWorldHint
a resource with both uri and uriTemplate, or neithermcp resource "post" needs uri or uriTemplate, not both
a template beyond level 1mcp resource "post": uriTemplate supports {name} expressions only (RFC 6570 level 1)
a uri or uriTemplate that is not a string literalserver/mcp.ts#mcp: mcp resource "post": uri and uriTemplate must be string literals; the build reads them
two expressions in one segmentmcp resource "post": uriTemplate has two {name} expressions between one pair of "/"; give each its own path segment
resourceMetadata on a route with a :param or *mcp.resourceMetadata needs a route without parameters or wildcards (got "/mcp/:tenant")
two resources with one uri (or one uriTemplate)mcp resource "copy": uri "posts://1" is already resource "post"
a prompt argument that is not a stringmcp prompt "review": argument "count" must be a string schema (MCP prompt arguments are strings)
resourceMetadata without serversmcp.resourceMetadata.authorizationServers must list at least one https: URL
resourceMetadata that is not literalserver/mcp.ts#mcp: mcp.resourceMetadata must be an object literal of string array literals; the build reads it

Calling a tool

tools/call runs the handler in process, as the server calls any handler: the arguments are its input, checked by its input; its middleware runs; ctx.event is the endpoint's request. The answer is a tool result:

The handlerThe result
returns a string{ content: [{ type: "text", text }] }
returns a Blob of type image/* or audio/*{ content: [{ type: "image", data, mimeType }] } (or audio), data in base64
returns another valueits JSON as text, plus structuredContent when the tool lists an outputSchema
returns a stream or a ResponseisError: Tool "searchPosts" returned a stream; an MCP tool answers one result
is given input its input refusesisError, one line per issue: limit: Number must be less than or equal to 50
throws a HamurError below 500 (a middleware's 401, createError({ status: 404 }), fail())isError with its message
throws anything elseisError with Internal error, the message in hamur dev; the error hook gets it with phase: "function"

An unknown tool is the JSON-RPC error -32602 Unknown tool: deletePosts.

Values mirrored into headers

A property of a tool's input schema may carry x-mcp-header: "Region", which asks a 2026-07-28 client to send its value as Mcp-Param-Region too, so a gateway can route on it. The endpoint checks the header against the argument on every such call: missing or different, the call answers 400 -32020 Header mismatch: Mcp-Param-Region header value 'us-east1' does not match body value 'us-west1'. Set the key through your schema library's metadata.

Resources

A resource is read by a handler. A uri entry is one resource; a uriTemplate entry is a family of them, written with RFC 6570 level 1 expressions ({id} only), at most one between two /. The sample above lists posts://{id}.

resources/list gives the uri entries and resources/templates/list the uriTemplate ones, each with name (the key), title (meta.summary), description (meta.description) and mimeType. resources/read { uri } takes an exact uri entry first, then the templates in the order written; a {name} matches one or more characters other than /, percent-decoded (a value that decodes to /, as %2F does, matches nothing; a URI above 2048 characters matches no template), and the matched variables are the handler's input, checked by its input (a uri entry's handler gets none).

The handlercontents[0]
returns a string{ uri, mimeType, text }, mimeType the entry's or text/plain
returns a Blob or Uint8Array{ uri, mimeType, blob }, blob in base64; mimeType the entry's, the Blob's type or application/octet-stream
returns another valueits JSON as text, mimeType the entry's or application/json

Errors are JSON-RPC errors, answered 200:

CaseError
no entry matches, or the handler throws a 404{"code":-32602,"message":"Resource not found: posts://9","data":{"uri":"posts://9"}}
input its input refuses-32602 Invalid arguments for resource "post", data: { issues }
a HamurError below 500 (a middleware's 401 or 403, fail())its status as the code: {"code":403,"message":"Forbidden","data":{"status":403}}
anything else-32603 Internal error, the message in hamur dev; the error hook gets it with phase: "function"

Prompts

A prompt is a handler whose input fields are strings; a field of another type fails tsc -b, and a property whose JSON Schema is not a string fails at definition. prompts/list gives name, title, description and arguments: one { name, description, required } per property of the input's JSON Schema, description from the property's and required from the schema's required.

prompts/get { name, arguments } runs the handler with arguments as its input. A string is one user message, { role: "user", content: { type: "text", text } }; an array of McpPromptMessage ({ role: "user" | "assistant", content }, a string content becoming text) is the messages. The result also carries the handler's meta.description.

CaseError
an unknown name-32602 Unknown prompt: review
input its input refuses-32602 Invalid arguments for prompt "review": id: Required
a HamurError below 500its status as the code, as for resources
a value that is neither a string nor messages-32603, logged once: mcp prompt "review" returned neither a string nor messages

The transport

The endpoint is stateless: every request is one POST with one JSON-RPC message, answered with one JSON object. There is no session, no Mcp-Session-Id and no event stream; GET and DELETE answer 405 with Allow: POST.

A 2026-07-28 request names its revision on every request, in the MCP-Protocol-Version header and in params._meta, and mirrors its method and tool name into Mcp-Method and Mcp-Name:

text
POST /mcp
content-type: application/json
accept: application/json, text/event-stream
mcp-protocol-version: 2026-07-28
mcp-method: tools/call
mcp-name: searchPosts
mcp-param-region: eu

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"searchPosts","arguments":{"query":"Hello","region":"eu"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}

A 2025-11-25 client starts with initialize, which answers protocolVersion: "2025-11-25", then sends MCP-Protocol-Version: 2025-11-25 on each request. It may leave out Mcp-Method, Mcp-Name and Mcp-Param-*, but one it sends must match the body as for a 2026-07-28 request.

MethodRevisionAnswer
server/discover2026-07-28supportedVersions, capabilities, instructions
initialize2025-11-25protocolVersion, capabilities, serverInfo, instructions
ping2025-11-25an empty result
tools/list, tools/callboththe tools; a tool result
resources/list, resources/templates/list, resources/readboththe resources; their contents
prompts/list, prompts/getboththe prompts; the messages

Every result carries resultType: "complete" and _meta["io.modelcontextprotocol/serverInfo"], the name and version of the app's package.json (hamur-app and 0.0.0 without them). server/discover and the four lists also carry ttlMs: 300000 (0 in hamur dev, where an edit of the endpoint's file or of a handler it lists rebuilds the server and changes the list) and cacheScope: "private"; resources/read carries ttlMs: 0. capabilities names tools, resources and prompts only for the keys the endpoint has. MCP_PROTOCOL_VERSIONS from hamur/server lists the revisions, newest first.

Refusals

The checks run in this order, each before the next:

RequestStatusAnswer
an Origin that is not the request's own origin (see Who may call) nor in server.originCheck.allow403-32600 Origin https://evil.test is not allowed
a content-type other than application/json415
an Accept that names neither application/json nor */*406MCP needs accept: application/json
a body above server.maxBodySize413
text that is not JSON400-32700 Parse error
a JSON array400-32600 MCP has no batches: send one JSON-RPC message per request
params that is an array400-32602 Invalid params: params must be an object
not a request, or a request whose id is null400-32600 Invalid Request
a notification202no body
no MCP-Protocol-Version (except initialize)400-32020 Header mismatch: MCP-Protocol-Version header is missing
a revision not in MCP_PROTOCOL_VERSIONS400-32022 Unsupported protocol version, data: { supported, requested }
a header that differs from params._meta400-32020 Header mismatch: MCP-Protocol-Version header value '2026-07-28' does not match body value '2027-01-01'
a 2026-07-28 request without its _meta fields400-32602 Invalid params: _meta["io.modelcontextprotocol/protocolVersion"] is required
a missing or different Mcp-Method or Mcp-Name400-32020 Header mismatch: Mcp-Name header value 'foo' does not match body value 'bar'
a method the revision does not have (ping in 2026-07-28, server/discover in 2025-11-25)404-32601 Method not found: ping

An error whose request id is not known has no id.

Who may call

The endpoint is a route, so the request steps of defineServer({ middleware }) and the endpoint's own middleware run before any message is read, and either may answer 401 or 403 for the whole endpoint, as requireToken does above. A tool's, resource's or prompt's own middleware decides per call; its refusal is an isError result for a tool and a JSON-RPC error for the others. Lists are the same for every caller: serve a second endpoint with its own middleware for callers who must see fewer tools.

An agent that calls with a user's token or session cookie does what that user may do: the tool runs as that user's request, and Hamur adds no confirmation step and no rate limit, so list only tools you would let the user's agent run.

A request without Origin (a desktop agent, a server, curl) passes the origin check. One with an Origin passes when server.originCheck.allow lists it, or when it is the request's own origin: with app.origin set, exactly that origin; without it, the request's host and port, and the host must also be a loopback name (localhost, 127.0.0.1, ::1) or one server.allowedHosts lists, since a DNS rebinding page sends its own name as both Host and Origin. Origin: null is refused. Set app.origin in production, as the config sample does.

Protected-resource metadata

With resourceMetadata, the endpoint also answers GET /.well-known/oauth-protected-resource<baseURL><route> (RFC 9728): /.well-known/oauth-protected-resource/mcp for the sample. It is the one path an endpoint answers outside app.baseURL, so a proxy that forwards only the base must forward it too. It is answered before the request steps of defineServer({ middleware }) and without the endpoint's own middleware, so a client without a token can read it. It is cache-control: public, max-age=3600 with app.origin set and private, max-age=3600 without it, since resource then follows the request's host.

json
{
  "resource": "https://blog.example.com/mcp",
  "authorization_servers": ["https://auth.example.com"],
  "bearer_methods_supported": ["header"]
}

resource is the endpoint's absolute URL from app.origin, so set it in production: without it the origin comes from the request. scopesSupported adds scopes_supported. A 401 answered for the endpoint's path, by the request steps or the endpoint's middleware, gets WWW-Authenticate: Bearer resource_metadata="https://blog.example.com/.well-known/oauth-protected-resource/mcp" unless it sets its own WWW-Authenticate. Hamur checks no token itself; the middleware does.

WebMCP: tools in the browser

An MCP endpoint answers agents that call the server. WebMCP is the other side: a page tells the browser's agent which tools it offers, and the agent calls them in the page, with the user's session and the page's own $fetch. It is experimental too, behind experimental.webmcp: true (a W3C Community Group draft, so the names may move), and adds no dependency. The browser decides what an agent may call; Hamur adds no confirmation step and no rate limit.

A file in app/tools/ default-exports defineTool({ … }) and is registered after hydration, for as long as the document lives. A browser with no model context registers nothing, and the page works as before. The rest of this section is what a page, a form or a module adds. The signatures are in the API reference.

Forms as tools

A <form> becomes a tool with attributes alone, and the browser builds its input from the fields and submits the form when an agent calls it. Hamur adds no runtime for it; each adapter types the attributes, so a typo fails tsc -b.

tsx
export default function SearchForm() {
  return (
    <form action="/search" toolname="search-posts" tooldescription="Search the posts by a word in the title">
      <input name="q" required toolparamdescription="The word to look for" />
      <select name="order" toolparamdescription="Newest first or oldest first">
        <option value="newest">Newest</option>
        <option value="oldest">Oldest</option>
      </select>
      <button type="submit">Search</button>
    </form>
  )
}
AttributeOnMeaning
toolnameformthe tool's name: 1 to 128 characters of A-Z, a-z, 0-9, _, - and .
tooldescriptionformthe tool's description
toolautosubmitformthe browser submits without asking the user first; a boolean attribute, "" in React
toolparamdescriptioninput, select, textareathe field's description

Two forms with one literal toolname in one page's imports fail the build: Two forms with toolname "search" on /: app/pages/index.tsx:12 and app/components/Search.tsx:4. A toolname that is also the name of an app/tools/ tool logs one warning, Form toolname "search" (app/components/Search.tsx:4) has the name of the WebMCP tool app/tools/search.ts; the browser keeps whichever registers first. A name that is not a string literal is not checked.

Page tools

A page declares tools of its own with a named tools export (in vue the non-setup <script>, in svelte <script module>). They are registered when the page has loaded and unregistered when a navigation leaves it, so a tool offered on /posts/1 is gone on /. A layout or a component cannot declare them. The inputSchema may be a valibot or zod schema, which also types input and checks the agent's input before execute runs.

ts
// app/pages/posts/[id].tsx
import { defineTool } from "hamur/app"

export const tools = [
  defineTool<{ length: "short" | "long" }>({
    name: "summarize-post",
    description: "Summarize the post on screen",
    inputSchema: { type: "object", properties: { length: { enum: ["short", "long"] } }, required: ["length"] },
    execute: ({ length }) => `A ${length} summary`,
  }),
]

A page tool with the name of an app/tools/ tool, or two with one name in a page, fails the build. annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint, title) and exposedTo (origins of the agents the tool is offered to) are keys of any tool.

Listing and running the tools

useTools() lists the tools the browser holds for the page, those of the app and of other scripts, and runs one by name:

ts
import { useTools } from "hamur/app"

export async function listTools(): Promise<string[]> {
  const tools = await useTools().list()
  return tools.map((tool) => `${tool.name}: ${tool.description}`)
}

export const runSearch = (query: string): Promise<unknown> => useTools().execute("search-posts", { query })

Without experimental.webmcp, on the server and in a browser with no model context, list() gives [] and execute rejects with WebMCP is not available in this browser. The tools:change app hook runs when any script registers or unregisters a tool.

Tools from a module

A module adds a tool with addTool({ src }), where src is the file of a default-exported defineTool(…):

ts
import { addTool, createResolver, defineModule } from "hamur/kit"

export default defineModule({
  meta: { name: "post-tools" },
  setup() {
    const { resolve } = createResolver(import.meta.url)
    addTool({ src: resolve("./runtime/search-tool.ts") })
  },
})
ts
import { defineTool } from "hamur/app"

export default defineTool<{ query: string }>({
  description: "Search the posts by a word in the title",
  annotations: { readOnlyHint: true },
  inputSchema: { type: "object", properties: { query: { type: "string" } }, required: ["query"] },
  execute: ({ query }) => `Posts about ${query}`,
})

The tool's name is name, else the one inside defineTool, else the file's. The app wins over layers and layers over modules: a tool whose name is taken is dropped, and the build logs once WebMCP tool "search" from module "x" is shadowed by app/tools/search.ts.