@crud-api/mcp
v0.7.0
Published
MCP Protocol adapter of the CRUD API reference implementation: a dependency-free tool layer for any CrudServer (tool definitions, capabilities, calls)
Maintainers
Readme
@crud-api/mcp
MCP Protocol adapter of the CRUD API reference implementation (MCP Protocol specification 0.2.0, specs/mcp, MCP revision 2026-07-28). The tool layer depends only on @crud-api/core (and its peer @ecson/core); it uses only standard APIs, no node:* module. ESM only, requires Node 24 or later (also runs on Bun and Deno). Apache-2.0.
This version has the tool definitions, the capability declaration, tool calls, the MCP Tasks extension for asynchronous operations, a JSON-RPC dispatcher and a binding to the official MCP TypeScript SDK v2 (subpath @crud-api/mcp/sdk).
import { createCrudServer } from "@crud-api/core";
import { createMcpTools } from "@crud-api/mcp";
const server = createCrudServer({ provider });
const mcp = createMcpTools(server, { collectionTools: ["orders"] });
await mcp.listTools(); // crud.get ... crud.delete, then orders.get ... orders.delete
mcp.capabilities(); // { tools: {}, extensions: { "dev.lingodata/crud": { specs: { base: "0.2.0" } } } }
await mcp.callTool("crud.list", { collection: "orders", query: { status: "paid" }, sort: "-total", limit: 2 }, { traceparent });
// { isError: false, structuredContent: [...], content: [{ type: "text", text: "[...]" }],
// _meta: { "dev.lingodata/crud.specs": { base: "0.2.0" }, "dev.lingodata/crud.matchedCount": 37, traceparent } }Tools
crud.get,crud.list,crud.create,crud.clone,crud.patch,crud.replace,crud.delete, each with acollectionargument (MCP_TOOLS).inputSchemais a JSON Schema 2020-12 object withpropertiesandrequired; it never setsadditionalProperties: false, so Custom Parameters can travel as extra arguments (MCP_ARGS_CUSTOM).- Annotations (MCP_TOOL_ANNOTATIONS):
readOnlyHinton reads,destructiveHintandidempotentHintoncrud.replaceandcrud.delete. collectionTools: ["orders"]addsorders.gettoorders.delete, without thecollectionargument (MCP_COLLECTION_TOOLS). A name must be a Slug other thancrud.- Extension arguments appear only when the Server supports the extension:
expandwith Relationships,ifMatchwith Metadata,crud.listByViewwithviewandviewParamswith Views. - With Metadata,
ifMatchoncrud.patch,crud.replaceandcrud.delete(and their Collection tool variants) is the expected_meta.hash, one string (MCP_ARGS_PRECONDITIONS). The write fails withPRECONDITION_FAILED, as a tool result withisError: true, and writes nothing when the hash differs or the Resource does not exist; withquery, every matched Resource must match. A value that is not a string isINVALID_INPUT(MCP_ARGS_FORMATS). Without Metadata,ifMatchis ignored withPARAM_IGNORED. Results carry_metawithversion,hashandeventsinstructuredContent, andMETA_IGNOREDWarnings indev.lingodata/crud.warnings. - With Schema (D152), see the Schema section below:
derive, thecrud.schema.*tools, schema-typed Collection tools and the MCP resources. - With Views (D164), see the Views section below:
crud.listByView, thecrud.views.*tools and a tool per View. - With Async (D175), see the Async section below: tool calls may return MCP tasks.
principal(context)(D175 item 8): the Client's identity for one request, fromcontext.meta(the request_meta) andcontext.authInfo(the validated token the host passes as the last argument ofhandle,callTool,getTask,cancelTaskandupdateTask,{ authInfo }, or the SDK binding takes from its request context). It becomesmeta.principalof every tool call (and of the View lookup behind a View tool) and theprincipalof everytasks/*lookup, so the host'sauthorizeand theowneroption of@crud-api/asynctell MCP Clients apart. A throw is theINTERNALtool error, or-32603ontasks/*; a value that is not a function is aTypeError. The reads oftools/listandresources/*carry no principal.- With Relationships,
expandoncrud.get,crud.listand their Collection tool variants is a field list of relationship Fields, a string or an array of strings, read likefields(MCP_ARGS_FORMATS): another type isINVALID_INPUT, and the engine checks the paths (-authorisINVALID_INPUT, REL_EXPAND). The referenced Resources come back in thedatamember of each$relinsidestructuredContent, andREFERENCE_NOT_FOUNDandEXPAND_IGNOREDWarnings indev.lingodata/crud.warnings.crud.createand the other writes keep only the reference:datais dropped (REL_WRITE_REFERENCE), andexpandthere is ignored withPARAM_IGNORED. Without Relationships,expandis ignored withPARAM_IGNOREDwhatever its type (D135).
Schema
With schema among the Server's specifications (Schema extension, MCP section 6, D152) the adapter maps it as follows. listTools() is asynchronous for this reason.
@schemaworks with the generic tools:crud.getwithcollection: "@schema"and the Slug of a Collection asid(MCP_SCHEMA_COLLECTION).crud.cloneon@schemaneedsnewId, or it isINVALID_INPUT(MCP_SCHEMA_CLONE).crud.schema.get,.list,.create,.clone,.patch,.replaceand.deleteare the tools of section 2 with the Collection fixed to@schemaand nocollectionargument (MCP_SCHEMA_TOOLS). There is nocrud.schema.listByView.derive(boolean) oncrud.create,crud.replace,crud.schema.createandcrud.schema.replaceis the engine'sderiveParameter. Another type isINVALID_INPUT(MCP_ARGS_FORMATS);derive,falseincluded, with a Collection other than@schemaisINVALID_INPUT(MCP_SCHEMA_DERIVE). The Collection tools<collection>.createand<collection>.replacedo not declare it, since their Collection is never@schema; aderivesent to them isINVALID_INPUTtoo. Without Schema it is ignored withPARAM_IGNORED.- Results of
crud.getandcrud.list(and Collection tools) of a Collection with a registered schema carry_meta["dev.lingodata/crud.schema"]with{ collection, version }(MCP_SCHEMA_META), read from the engine'sannotations.schema;versionisnullwhen the schema has none. - Collection tools (
collectionTools) of a Collection with a registered schema declare its compiled schemaS(ESType) as theresourceargument ofreplace, andanyOf: [S, { type: "array", items: S }]asresourcesofcreate(MCP_SCHEMA_INPUT).listTools()reads the schemas withliston@schemaandcompiled: trueon every call and caches nothing; if that read fails, the tools keep their generic argument types.Sbecomes a subschema of the tool'sinputSchema, so a schema without an$idis embedded with$id: "lingodata-crud://schema/<collection>"(the URI of its MCP resource):$idstarts a new schema resource (JSON Schema 2020-12), so$ref: "#/$defs/..."inside it still resolves againstS. A schema that already has an$idkeeps it. The genericdescriptionof the argument stays beside the schema forresource(the schema's own wins) and on theanyOfwrapper forresources. A compiled schema that cannot be copied leaves the tools of its Collection generic. An$idcan name only one schema of a document, so in the array formitemsis{ "$ref": "<the $id>" }and not a second copy ofS. - No tool declares an
outputSchema(MCP_SCHEMA_OUTPUT, D150):fieldscan drop required Fields, and a lenient schema does not describe what is stored. - Resources (MCP_SCHEMA_RESOURCES): the capability
resources: {},resources/templates/list(the templatelingodata-crud://schema/{collection},application/json),resources/list(one resource per schema Resource, Collections without a schema included, in one page; the adapter reads every page of@schema, by cursor or by offset) andresources/read(the schema Resource as plain JSON text). The same methods arelistResourceTemplates(),listResources()andreadResource(uri), and the SDK binding registers the three handlers. A malformed or unknown URI is-32602; a Collection that does not exist is-32602"Resource not found" with{ uri }indata, which is what MCP2026-07-28requires (the-32002of earlier revisions is only accepted by clients). - Errors and Warnings (MCP_SCHEMA_ERRORS): the
errorsmember of the Problem Details and theinstanceandkeywordmembers ofSCHEMA_VIOLATIONWarnings pass as the engine produced them. - Every call carries
meta.input: "ecson"to the engine (MCP_ARGS_ECSON): arguments are always read as ECSON.
Views
With the Views extension among the Server's specifications (MCP section 2.3, D164):
crud.listByView(and<collection>.listByView) takescollection,view(a string: missing isINVALID_INPUT, rule MCP_TOOLS; another type, rule MCP_ARGS_FORMATS),viewParams(an object read as ECSON, so{ "$date": ... }is aDate) and the arguments ofcrud.list, which combine with the View (thequerynarrows it,fieldsintersect,sortorders its ties).- The tools of section 2 accept
<collection>/@viewsascollection, with a View name asid(MCP_VIEWS_COLLECTION). crud.views.get,.list,.create,.clone,.patch,.replaceand.delete(MCP_VIEWS_TOOLS) are those tools on<collection>/@views, withcollection(required) the Collection whose Views they manage; they are listed aftercrud.schema.*.viewTools: ["orders"](MCP_VIEW_TOOLS) adds one tool per View of each listed Collection,orders.<view>, listed after every other tool: titleView <view> of orders, the View'sdescription,readOnlyHint, nooutputSchema, and aninputSchemawith the View parameters (from its compiledparams,requiredincluded,$defshoisted) besides the optional arguments ofcrud.list.listTools()reads the Views on every call (listonorders/@views, every page: by cursor, or by offset when the engine reportshasNextwithout a cursor, as undermaxLimit); when that fails, the other tools are still listed. A call resolves the View with oneget; a View that no longer exists is JSON-RPC-32602unknown tool. Parameter arguments becomeviewParams; unknown arguments are Custom Parameters (PARAM_IGNORED). A View gets no tool (S77) when its name is a Collection tool suffix (list,get, ...), a parameter is named like an argument ofcrud.list(orexpand,ifMatch,derive) or like a Server Custom Parameter (MCP_ARGS_CUSTOM), or the tool name would exceed 128 characters;crud.listByViewstill runs it.viewToolsentries must be Slugs other thancrud(TypeError), and are ignored without Views.
Async (MCP Tasks)
With the Async extension among the Server's specifications (createCrudServer({ extensions: [asyncOperations()] }), @crud-api/async; MCP section 5, D175), long operations run as tasks of the MCP Tasks extension (io.modelcontextprotocol/tasks, revision 2026-07-28):
const meta = {
"io.modelcontextprotocol/clientCapabilities": { extensions: { "io.modelcontextprotocol/tasks": {} } },
"dev.lingodata/crud.async": "prefer",
};
const task = await mcp.callTool("crud.delete", { collection: "orders", query: { status: "cancelled" } }, meta);
// { resultType: "task", taskId: "01a2...", status: "working", createdAt, lastUpdatedAt, ttlMs: 86400000, pollIntervalMs: 1000, _meta }
await mcp.getTask(task.taskId, meta);
// { taskId, status: "working", statusMessage: "1200 of 5000 items done", ... }, later
// { taskId, status: "completed", ..., result: { resultType: "complete", isError: false, structuredContent: null, _meta: { ... } } }- Capability:
capabilities()addsextensions["io.modelcontextprotocol/tasks"] = {}besidedev.lingodata/crud(TASKS_EXTENSION_ID). - Declaration (MCP_ASYNC_TASKS): the request
_metakeydev.lingodata/crud.asyncis"prefer"or"require"(another value isINVALID_INPUT, rule MCP_ASYNC_TASKS), and counts only when the same request declares the Tasks capability in_meta["io.modelcontextprotocol/clientCapabilities"].extensions. Without the capability,preferruns synchronously andrequireis the tool execution errorNEGOTIATION(rule MCP_ASYNC_NEGOTIATION). With the capability and no key, an operation that runs only asynchronously becomes a task and the others run synchronously (S90). -32021(MCP_ASYNC_NEGOTIATION): an operation that runs only asynchronously, for a Client without the Tasks capability, is the JSON-RPC errorMissingRequiredClientCapability(MISSING_REQUIRED_CLIENT_CAPABILITY) withdata: { requiredCapabilities: { extensions: { "io.modelcontextprotocol/tasks": {} } } }, whatever the key says; nothing runs.requireon an operation that runs only synchronously is the tool execution errorNEGOTIATION.- Task (MCP_ASYNC_CREATE_TASK, MCP_ASYNC_EXPIRES): an accepted call returns the flat
CreateTaskResult{ resultType: "task", taskId, status: "working", createdAt, lastUpdatedAt, ttlMs, pollIntervalMs, _meta }: the Operation ID astaskId, ISO 8601 times,ttlMssuch thatcreatedAt + ttlMsis the state'sexpiresAt(it grows when completion extends the retention), and the usual result_meta(specs, the Warnings found so far,traceparent). Failures found before the accept are ordinary tool results (S87). tasks/get(getTask(taskId, _meta); MCP_ASYNC_RESULT, MCP_ASYNC_PROGRESS): requires the Tasks capability on that request (else-32021). A working task carries progress instatusMessage("<done> of <total> items done", or"<done> items done"); no progress notification is sent, since MCP Tasks forbids them for tasks (S89). A completed task (MCP'sfailedstatus is never used: CRUD failures are tool results) hasstatus: "completed"andresult, the tool result the synchronous call would have returned (isErrorfalse or true, its_meta), rendered by the same function, withresultType: "complete". An unknown, foreign, malformed or expiredtaskIdis-32602with the CRUD error (code: "NOT_FOUND",target: "operation", nostatus) indata(S93); anACCESS_DENIEDfromauthorizeis-32602too, and a Server failure-32603with the genericINTERNALProblem.tasks/cancelandtasks/update(cancelTask,updateTask): checked astasks/get, acknowledged with an empty result, and change nothing: CRUD operations cannot be cancelled and never wait for input (S94).- Authorization (MCP Tasks: "Servers MUST perform authentication and authorization checks on each task-related request"): every
tasks/*lookup goes through the host'sauthorizewith theprincipaloption's value, and withasyncOperations({ owner })a task is found only by a request whose principal gives its owner; another Client gets-32602"Task not found", as for an unknown ID. Withoutprincipal, MCP lookups carry no identity, soownerfinds only tasks stored without an owner.
const mcp = createMcpTools(server, { principal: ({ authInfo }) => (authInfo === undefined ? undefined : { sub: (authInfo as { clientId: string }).clientId }) });
await mcp.handle(message, { authInfo }); // the token the host verifiedcallToolreturnsCallToolResult | CreateTaskResult: TypeScript hosts that read.isErrormust first narrow on"resultType" in result(a breaking type change of 0.7.0). A synchronous tool result still has noresultType(handleadds it on the wire), whilegetTask(...).resultcarriesresultType: "complete".- Without Async, the key is ignored, no Tasks capability is advertised and
tasks/*are-32601.
Capabilities
capabilities() returns what the Server advertises in server/discover (MCP_EXTENSION_ID): tools, resources with the Schema extension, the io.modelcontextprotocol/tasks extension with Async, and the dev.lingodata/crud extension, whose specs hold the highest supported version of each specification the Server implements.
Tool calls
callTool(name, arguments, _meta) runs one operation through the Server and returns the MCP tool result, or a CreateTaskResult when it runs as a task (Async section).
- Arguments (MCP_ARGS_FORMATS, MCP_ARGS_ECSON):
queryis UnQuery JSON as an object or UnQuery SQL as a string;fieldsandsortare strings or arrays of field paths;page,limitandoffsetare integers; Resources, patches (valueof JSON Patch operations, whole Merge Patch documents) and query operands are read as ECSON with the Server's codec.crud.patch,crud.replaceandcrud.deletetakeidorquery, never both (MCP_TOOLS). - An argument that is neither of the tool nor a Custom Parameter of the Server is ignored with a
PARAM_IGNOREDWarning (MCP_ARGS_CUSTOM). Extension arguments the Server does not map are ignored the same way. - Request
_meta(MCP_META_KEYS):dev.lingodata/crud.require,.prefer,.handling,.allowedWarnings, andtraceparent, whose trace-id is the Correlation ID (MCP_META_TRACEPARENT)..asynccounts only with the Async extension and the Tasks capability (Async section); otherwise it is ignored. - Results (MCP_RESULT_STRUCTURED):
structuredContentis the Resource, the list, the written list ornull, in ECSON, andcontenthas the same value as text._metahas.specs,.matchedCount,.modifiedCount,.upserted,.warnings,.nextCursorand the request'straceparent, when they apply. - Errors: a failed operation, including an argument of the wrong type, is a tool result with
isError: trueand the Problem Details object, withoutstatus(MCP_ERROR_TOOL_RESULT, MCP_ERROR_META, MCP_STRICT_WARNINGS). Only an unknown tool or a malformed request rejects, withMcpProtocolError(JSON-RPC-32602, MCP_ERROR_PROTOCOL).
JSON-RPC
handle(message) answers one parsed JSON-RPC message of MCP 2026-07-28 (the modern era: no initialize handshake, every request carries its protocol version), so any transport that delivers JSON-RPC messages can serve the tools without the SDK.
const mcp = createMcpTools(server, { serverInfo: { name: "orders-api", version: "1.0.0" } });
await mcp.handle({
jsonrpc: "2.0", id: 1, method: "server/discover",
params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {} } },
});
// { jsonrpc: "2.0", id: 1, result: { resultType: "complete", supportedVersions: ["2026-07-28"], capabilities: { ... },
// ttlMs: 0, cacheScope: "private", _meta: { "io.modelcontextprotocol/serverInfo": { name: "orders-api", version: "1.0.0" } } } }server/discoverreturns the supported versions andcapabilities();tools/listreturnslistTools()in one page; both carryttlMs: 0andcacheScope: "private". With Schema,resources/templates/list,resources/listandresources/readanswer as the Schema section says, also withttlMs: 0andcacheScope: "private"(a cursor on the lists is-32602); without it they are-32601.tools/callreturns the tool result ofcallToolwithresultType: "complete", or itsCreateTaskResult(resultType: "task"). With Async,tasks/get,tasks/cancelandtasks/updateanswer as the Async section says; without it they are-32601.serverInfo, when configured, goes to the_metaof every result.- JSON-RPC errors (MCP_ERROR_PROTOCOL):
-32600for a malformed message (theidisnullwhen it cannot be read),-32601for any other method (includinginitialize, whose error names the supported versions),-32602for missing per-request_metafields, a cursor, an unknown tool or malformedtools/callparams, and-32022(UnsupportedProtocolVersionError, withdata.supportedanddata.requested) for another protocol version (MCP_VERSION). A notification resolvesnull.handlenever rejects.
Binding to the official SDK
The subpath @crud-api/mcp/sdk binds the tool layer to the official MCP TypeScript SDK v2. @modelcontextprotocol/server (^2.4.0) is an optional peer dependency: install it only to use the subpath; the main entry never imports it.
import { createMcpTools } from "@crud-api/mcp";
import { createMcpFetchHandler, createSdkServer } from "@crud-api/mcp/sdk";
const mcp = createMcpTools(server, { collectionTools: ["orders"] });
const fetchHandler = createMcpFetchHandler(mcp, { name: "orders-api", version: "1.0.0" });
// (request: Request) => Promise<Response>: MCP 2026-07-28 over Streamable HTTP, on any web-standard host
Deno.serve((request) => fetchHandler(request));
const sdkServer = createSdkServer(mcp, { name: "orders-api", version: "1.0.0" }); // a low-level SDK ServercreateSdkServer(tools, info)returns a low-level SDKServerthat declarestools.capabilities()(with thedev.lingodata/crudextension) and handlestools/listwithlistTools()andtools/callwithcallTool(name, arguments, _meta), and, with the Schema extension,resources/templates/list,resources/listandresources/read. TheMcpProtocolErrorofcallTool(an unknown tool, malformed params) becomes the SDK'sProtocolErrorwith the same code, message and data; a cursor ontools/listis-32602, as inhandle.createMcpFetchHandler(tools, info)serves MCP2026-07-28with the SDK'screateMcpHandler, statelessly (oneServerper request). Its handler takes(request, { authInfo }?): the host verifies the token and passes the SDKAuthInfo, which the handlers read fromctx.http.authInfoand hand to theprincipaloption (D175 item 8). The SDK answersserver/discoverand checks the protocol headers. Clients of the 2025 revisions (initialize) are refused with-32022naming2026-07-28, since the 2025 wire cannot carry the arraystructuredContentofcrud.listand other tools.- With Async, the binding serves the whole task flow (D175): the Tasks capability passes through the SDK's
server/discover;tasks/get,tasks/cancelandtasks/updateare registered withsetRequestHandlerand explicit schemas (the SDK would otherwise answer the 2025 methodstasks/getandtasks/cancelwith-32601); the SDK moves theio.modelcontextprotocol/*keys out ofparams._metainto its request envelope, and the binding joins them again so the Tasks capability is seen; and the server class overrides the SDK'sServer._wrapHandlerfortools/callto remove thecontent: []the SDK adds to a task result, so the wireCreateTaskResultis the flat MCP Tasks shape. That override relies on an SDK internal (tested on 2.4.0; the peer range is^2.4.0). TheMcp-Nameheader that MCP Tasks asks Streamable HTTP clients to send ontasks/*is neither required nor checked. - The SDK
Client2.4.0 does not support tasks:client.callToolrejects aCreateTaskResultwithSdkErrorUNSUPPORTED_RESULT_TYPEafter the Server sent it. Hosts on that client send the call withclient.request({ method: "tools/call", params }, schema)and a schema that acceptsresultType: "task", and calltasks/getthe same way. - An SDK
Clientmust negotiate the modern era:new Client(info, { versionNegotiation: { mode: { pin: "2026-07-28" } } })(ormode: "auto") withStreamableHTTPClientTransport. - The SDK depends on
zodat run time. The low-levelServerdoes not validate arguments againstinputSchema: the tool layer checks them, so an argument of the wrong type is a tool execution errorINVALID_INPUT, never a JSON-RPC error (MCP_ERROR_PROTOCOL). Onlyargumentsthat is not an object fails in the SDK, with-32602.
Conformance
conformance declares the MCP Protocol specification 0.2.0 (vector spec id @crud-api/mcp, MCP revision 2026-07-28) over the CRUD Base specification 0.2.0.
import { conformance } from "@crud-api/mcp";The package implements every rule of the MCP specification, those of the extension mappings included; 138 Base vectors, 25 Metadata vectors, 23 Relationships vectors, 64 Schema vectors, 48 Views vectors and 21 Async vectors (conformance/vectors/mcp/, op mcp, run by the repository runner against handle over @crud-api/memory) cover them, and conformance/COVERAGE.md lists each rule.
Limits
- Every extension is mapped: Metadata (
ifMatch, D126), Relationships (expand, D135), Schema (D152), Views (crud.listByView,crud.views.*and theviewToolsoption with a tool per View, D164) and Async (MCP Tasks, D175). Other extension arguments are ignored withPARAM_IGNORED. - Async: progress travels only in
statusMessage(S89);tasks/canceldoes not cancel (S94); a task still working when its process stops staysworkinguntil it expires (the in-process runner of@crud-api/async); the nestedresultof a completed task does not get theserverInfo_metaa synchronous result gets. - Only the modern era (
2026-07-28) is served. A 2025 revision Client (initialize) is refused with-32022: that wire cannot carry the arraystructuredContentofcrud.list(D105, D107). - Nesting depth (D108, closing the limit of D104): a Resource the Server could not encode back inside a list (deeper than 999 levels with the default ECSON
DEPTH_LIMITof 1000, typed values counted in their ECSON form) is refused by the core withINVALID_INPUT(ecsonCode: "DEPTH_LIMIT") before anything is written, forcrud.create,crud.clone,crud.patchandcrud.replace; arguments are read with the codec's limit, and aqueryobject deeper than 1000 levels isINVALID_INPUTtoo. A Server built with a codec whosemaxDepthis below 1000 is still checked against 999 for plain Resources. structuredContentof a Server without ECSON is plain JSON, which loses the precision of typed values (S41). The base example of an MCP error and the client side of the extension are open in the specification (S43, S44).- The readings chosen for the MCP rules are D102 to D107 in
docs/decisions.mdand S40 to S44 indocs/spec-issues.md.
