MCP servers (mcp, stdlib)

To start a server project, use radlang new myserver --template mcp, then cd myserver and radlang run. The bundled starter includes a typed greet tool, a localhost /mcp endpoint, HTTP test and client examples. It imports MCP from its pinned lib/stdlib.rlp. See new projects.

mcp wraps the existing httpserver to expose named tools over Streamable HTTP. Import it from stdlib; the HTTP server remains responsible for sockets, TLS, middleware, worker configuration and shutdown. Requires Radlang 1.26.3 or newer and a rebuilt stdlib package containing mcp.

A small server

import { mcp } from stdlib

fn main() {
    var app = mcp.create("my-tools", "1.0.0")
    app.addTool("hello", fn(): mcp.Result {
        return mcp.text("Hello from Radlang")
    })
    HttpServer web = httpserver.serve(8080, "127.0.0.1")
    mcp.mount(web, app)
    web.listen()
}

Connect an MCP HTTP client to http://127.0.0.1:8080/mcp. For predictable local resource use, set project.cores: 1 in config.yaml; otherwise existing HTTP worker configuration applies. Tool registration runs before listening in every worker, and there is no process-local protocol session to share.

Register tools

  • app.addTool(name, fn(): mcp.Result) registers a parameterless tool.
  • mcp.addTool(app, name, callback) is the namespace equivalent.
  • mcp.addTool(app, name, description, callback) adds a description.
  • mcp.addTypedTool<T>(app, name, description, inputSchema, fn(T): mcp.Result) registers typed arguments.
  • mcp.addTypedToolWithHints<T>(app, name, description, inputSchema, annotations, callback) also sets tool annotations. Build them with mcp.hints(readOnly, destructive, idempotent, openWorld).

Names are unique, case-sensitive, 1–128 ASCII letters/digits/underscore/hyphen/dot. Duplicate or invalid registrations throw. Registration is sealed when mounted; register all tools first. Definitions retain registration order. Treat the server’s registry fields as implementation state; do not mutate them directly. Schema and origin inputs are copied to protect configuration from later changes. Callbacks may capture application values; application state is subject to the HTTP server’s existing concurrency and process boundaries.

type GreetingArgs { string name }
type GreetingResult { string greeting }

fn installGreeting(mcp.Server app) {
    map[string, mcp.Schema] properties = json.parse<mcp.SchemaMap>('{}')
    properties.set("name", mcp.stringField("Name to greet"))
    mcp.addTypedTool<GreetingArgs>(app, "greet", "Greet someone",
        mcp.object(properties, ["name"]),
        fn(GreetingArgs args): mcp.Result {
            return mcp.structured<GreetingResult>(GreetingResult("Hello, " + args.name))
        })
}

Arguments are validated against the input schema and then parsed from the original request with the existing json.parse<T>. Large integers are not serialized through a float before reaching the callback. Missing required fields, wrong kinds and out-of-range typed integers are protocol errors, and the handler is not executed. An omitted arguments object means an empty object. Explicit null arguments are invalid. The declared type and schema should describe the same shape; schema validation and typed decoding both apply.

Schemas and results

Builders: stringField(description), integerField(description), numberField(description), booleanField(description), arrayOf(itemSchema), object(properties, requiredNames) and emptySchema().

For constraints, construct a typed mcp.Schema with json.parse<mcp.Schema> from JSON produced by json.from on a declared value. The supported JSON Schema vocabulary is deliberately bounded: type, description, properties, required, boolean additionalProperties, items, numeric minimum/maximum, string minLength/maxLength, and string enum. Types include object, array, string, integer, number, boolean and null. Unknown keywords, incompatible keywords, invalid bounds and nesting beyond 24 are rejected at registration. This is not a full JSON Schema engine; $ref, composition and regular-expression keywords are not supported. String lengths count Unicode code points. Numeric schema bounds use Radlang float precision; typed integer decoding remains exact.

  • mcp.text(text) returns text content.
  • mcp.structured<T>(object) returns typed structuredContent plus a text JSON representation for clients using text content. The value must be an object for compatibility with both supported protocol versions.
  • mcp.failure(message) returns a tool result with isError: true.
  • A thrown callback error produces a generic tool failure without exposing its private error details. Catch expected application failures and return mcp.failure when the client needs an actionable message.

Callbacks currently execute synchronously. Use synchronous service APIs in a namespace callback. Async tool registration, progress/cancellation streams, resources and prompts are follow-up additions; the server advertises only tools.

Mounting, policy and protocol support

mcp.mount(web, app) installs /mcp. For an explicit endpoint and allowed origins:

string[] origins = ["https://my-client.example"]
mcp.mount(web, app, "/mcp", origins)

Existing HTTP middleware can authenticate and authorize requests before the MCP route executes. Binding to loopback and checking Origin are not authentication. For remote deployments configure authentication/authorization and TLS through HTTP middleware or a trusted gateway; OAuth discovery/token issuance are not provided by this module. The default empty origin list rejects any supplied Origin; non-browser clients without Origin are accepted. CORS configuration is separate from MCP origin validation. The wrapper does not change the host server’s body limit or policy for other routes. Its own body limit is 1 MiB, with bounded JSON parsing and schema nesting.

Requests are POST with Content-Type: application/json (otherwise 415) and an Accept header naming both application/json and text/event-stream (otherwise 406). A request with a disallowed Origin gets 403 before either check. ping returns an empty result object {} (stdlib 1.1.3 or newer, built with Radlang 1.40.29 or newer; earlier stdlib builds returned the string "{}").

Both adapters return ordinary JSON responses, which Streamable HTTP permits. No SSE endpoint, resumability, session IDs or long-lived subscriptions are advertised. GET and DELETE on the MCP route return 405.

  • 2026-07-28: per-request metadata and matching MCP-Protocol-Version, Mcp-Method and, for tools/call, Mcp-Name headers. Supports server/discover, ping, tools/list and tools/call. Base64 sentinel names are decoded before header/body comparison. Unknown methods return HTTP 404 with JSON-RPC -32601.
  • 2025-11-25: stateless HTTP initialization and initialized notifications, followed by ping, tools/list and tools/call. No server-issued session ID is needed; the client supplies the negotiated version on subsequent requests.
  • Unsupported versions return a version error listing these two supported versions. The deprecated 2024 HTTP+SSE transport is not implemented.

Tool input errors are JSON-RPC -32602; callback failures are tool results with isError. Request IDs preserve string/integer values. Notifications never trigger a tool call. Tool lists are returned in a single page; any cursor, including an empty string, is rejected with -32602 because there is no additional page.

Protocol references: 2026 transport, tools, discovery, 2025 transport.

Building and testing

The normal stdlib build/export and distribution staging discover ns/mcp.ns.rad automatically. radlang new copies the resulting bundled library alongside the other stdlib namespaces. Rebuild/re-export a custom stdlib package to add MCP.

libraries/stdlib/test/mcp.test.rad tests the public result and registration helpers. python3 tests/integration/http/mcp.py target/release/radlang uses an independent Python HTTP client against a small loopback server, removes namespace sources, and tests both .rlc and .rlp imports, both protocol adapters and bounded concurrent calls. No external MCP SDK or model is needed. This is wire-contract acceptance rather than a claim of certification against every MCP client.