mcp.ts
This file
Path
packages/protocol/src/mcp.ts
188 lines · 7.1 KiB · TypeScript
Last changed by
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–90why, one step back1// Ported from joelhooks/rat-stack@fba26d8 `packages/capability/src/to-toolkit.ts`2// l.18–146, and ours to change since: it projects the contracts' Rpcs, with3// hints from our own annotations, not Rat Stack's capabilities. Rat Stack's4// licence travels with the code it copied:5//6// MIT License7//8// Copyright (c) 2026 Joel Hooks9//10// Permission is hereby granted, free of charge, to any person obtaining a copy11// of this software and associated documentation files (the "Software"), to deal12// in the Software without restriction, including without limitation the rights13// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell14// copies of the Software, and to permit persons to whom the Software is15// furnished to do so, subject to the following conditions:16//17// The above copyright notice and this permission notice shall be included in all18// copies or substantial portions of the Software.19//20// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR21// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,22// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE23// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER24// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,25// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE26// SOFTWARE.2728import type { JsonSchema, Layer } from "effect";29import { Context, Effect, JsonPointer, Predicate, Schema } from "effect";30import { Tool, Toolkit } from "effect/ai";31import type { Rpc, RpcClient, RpcClientError, RpcGroup } from "effect/rpc";3233import {34 Description,35 Destructive,36 Idempotent,37 NeedsApproval,38 ReadOnly,39} from "./annotations.ts";40import type { Unauthenticated } from "./principal.ts";4142type CallError = RpcClientError.RpcClientError | Unauthenticated;4344export type ToolOf<R extends Rpc.Any> =45 R extends Rpc.Rpc<46 infer Tag,47 infer Payload,48 infer Success,49 infer Error,50 infer _Middleware,51 infer _Requires52 >53 ? Tool.Tool<54 Tag,55 {56 readonly failure: Error;57 readonly failureMode: "error";58 readonly parameters: Payload;59 readonly success: Success;60 }61 >62 : never;6364export type ToolsOf<Rpcs extends Rpc.Any> = {65 readonly [R in Rpcs as R["_tag"]]: ToolOf<R>;66};6768export interface ToolListing {69 readonly name: string;70 readonly description: string;71 readonly annotations: {72 readonly readOnlyHint: boolean;73 readonly idempotentHint: boolean;74 readonly destructiveHint: boolean;75 readonly openWorldHint: boolean;76 };77 readonly inputSchema: JsonSchema.JsonSchema;78 readonly outputSchema: JsonSchema.JsonSchema;79}8081/**82 * The definition a `$ref` names, read as Effect reads it: a URI fragment83 * (percent-encoded, then `~1` and `~0` escaped) of the form `#/$defs/<key>`.84 */85const definitionKey = ($ref: string) => {86 const tokens = JsonPointer.parseUriFragment($ref);8788 return tokens?.length === 2 && tokens[0] === "$defs" ? tokens[1] : undefined;89};90Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
line 91why, one step back91/** Derived the way `McpServer` derives a tool's: a top-level `$ref` is inlined. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 92–128why, one step back92export const toJsonSchema = (schema: Schema.Top): JsonSchema.JsonSchema => {93 const { definitions, schema: root } = Schema.toJsonSchemaDocument(schema);9495 const key = Predicate.isString(root.$ref)96 ? definitionKey(root.$ref)97 : undefined;9899 const inlined = (key === undefined ? undefined : definitions[key]) ?? root;100101 return Object.keys(definitions).length === 0102 ? inlined103 : { ...inlined, $defs: definitions };104};105106export const listTools = <Tools extends Readonly<Record<string, Tool.Any>>>(107 toolkit: Toolkit.Toolkit<Tools>108): readonly ToolListing[] =>109 Object.entries(toolkit.tools).map(([name, tool]) => ({110 annotations: {111 destructiveHint: Context.get(tool.annotations, Tool.Destructive),112 idempotentHint: Context.get(tool.annotations, Tool.Idempotent),113 openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),114 readOnlyHint: Context.get(tool.annotations, Tool.Readonly),115 },116 description: Tool.getDescription(tool) ?? "",117 inputSchema: toJsonSchema(tool.parametersSchema),118 name,119 outputSchema: toJsonSchema(tool.successSchema),120 }));121122export interface ToolkitProjection<Rpcs extends Rpc.AnyWithProps, R> {123 readonly toolkit: Toolkit.Toolkit<ToolsOf<Rpcs>>;124 readonly layer: Layer.Layer<Tool.HandlersFor<ToolsOf<Rpcs>>, never, R>;125}126127const ASKS_FIRST = " Asks a person first.";128Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
lines 129–130why, one step back129// Every hint is explicit: MCP's defaults read an unannotated tool as130// destructive and open-world.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 131–188why, one step back131const toTool = (rpc: Rpc.AnyWithProps) => {132 const description = Context.get(rpc.annotations, Description);133134 return Tool.make(rpc._tag, {135 description: Context.get(rpc.annotations, NeedsApproval)136 ? `${description}${ASKS_FIRST}`137 : description,138 failure: rpc.errorSchema,139 parameters: rpc.payloadSchema,140 success: rpc.successSchema,141 })142 .annotate(Tool.Readonly, Context.get(rpc.annotations, ReadOnly))143 .annotate(Tool.Idempotent, Context.get(rpc.annotations, Idempotent))144 .annotate(Tool.Destructive, Context.get(rpc.annotations, Destructive))145 .annotate(Tool.OpenWorld, false);146};147148export const toToolkit = <Rpcs extends Rpc.AnyWithProps, R>(149 group: RpcGroup.RpcGroup<Rpcs>,150 client: Effect.Effect<RpcClient.RpcClient<Rpcs, CallError>, never, R>151): ToolkitProjection<Rpcs, R> => {152 const rpcs = [...group.requests.values()];153154 const made: unknown = Toolkit.make(...rpcs.map(toTool));155 // SAFETY: `Toolkit.make` is variadic over a tuple of tools; `ToolsOf<Rpcs>` recovers the tuple's type, which `map` over the runtime array cannot carry.156 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the tuple type is out of `map`'s reach; see SAFETY.157 const toolkit = made as Toolkit.Toolkit<ToolsOf<Rpcs>>;158159 const layer = toolkit.toLayer(160 Effect.map(client, (calls) => {161 // SAFETY: an RpcClient for a group without prefixes has one method per tag, and the toolkit decodes a tool's parameters with that Rpc's payload schema before calling it.162 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a loop over tags cannot name each Rpc's method; see SAFETY.163 const byTag = calls as Readonly<164 Record<165 string,166 (167 payload: Rpc.Payload<Rpcs>168 ) => Effect.Effect<Rpc.Success<Rpcs>, Rpc.Error<Rpcs> | CallError>169 >170 >;171172 // Each handler passes the payload alone: the toolkit's second argument173 // is its own context, which the client would read as call options.174 const handlers: unknown = Object.fromEntries(175 Object.entries(byTag).map(([tag, call]) => [176 tag,177 (payload: Rpc.Payload<Rpcs>) => call(payload),178 ])179 );180181 // SAFETY: the record is keyed by the group's tags, which are exactly the toolkit's tool names, and each value calls that tag's Rpc.182 // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `fromEntries` cannot carry the mapped type; see SAFETY.183 return handlers as Toolkit.HandlersFrom<ToolsOf<Rpcs>>;184 })185 );186187 return { layer, toolkit };188};