Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/agent-context-budget.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ name: Agent Context Budget
# Fails when a PR raises a value in agentContextBudget.json above main's. AgentContextBudget.test.ts
# keeps that file equal to the measured context, so the context cannot grow by editing the file.
# To accept growth on purpose, a maintainer adds the agent-context-increase label.
# mcpPackToolListJsonBytes is recorded, not gated: pack tools load on demand (McpToolExposure.ts).
on:
pull_request:
types: [opened, synchronize, reopened, labeled, unlabeled]
Expand Down Expand Up @@ -40,6 +41,7 @@ jobs:
git show "HEAD^1:$BUDGET" > "$RUNNER_TEMP/main.json"
grown=$(jq -r --slurpfile main "$RUNNER_TEMP/main.json" '
to_entries[]
| select(.key != "mcpPackToolListJsonBytes")
| select($main[0][.key] != null and .value > $main[0][.key])
| "\(.key): \($main[0][.key]) -> \(.value) (+\(.value - $main[0][.key]))"
' "$BUDGET")
Expand Down
1 change: 1 addition & 0 deletions apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"record:fx-replay": "node scripts/record-fx-acp-replay-fixture.ts",
"record:kiro-replay": "node scripts/record-kiro-acp-replay-fixture.ts",
"record:muse-replay": "node scripts/record-muse-msp-replay-fixture.ts",
"probe:mcp-relist": "node scripts/mcp-relist-probe.ts",
"generate": "graphqlgen",
"generate:expo-schema": "node scripts/fetch-expo-schema.ts"
},
Expand Down
114 changes: 114 additions & 0 deletions apps/server/scripts/mcp-relist-probe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Serves T3's real MCP transport with a hidden tool, to see whether a harness lists tools again
// after `tool_search`, before T3 defers tools for it (docs/operations/06_mcp-tool-deferral.md).
// @effect-diagnostics-next-line nodeBuiltinImport:off -- NodeHttpServer.layer takes Node's createServer.
import * as NodeHttp from "node:http";

import { NodeHttpServer, NodeRuntime } from "@effect/platform-node";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
EnvironmentId,
OrchestratorMcpFailure,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import { Tool, Toolkit } from "effect/ai";
import { Command, Flag } from "effect/cli";
import { HttpRouter } from "effect/http";

import * as McpHttpServer from "../src/mcp/McpHttpServer.ts";
import type * as McpInvocationContext from "../src/mcp/McpInvocationContext.ts";
import * as McpSessionRegistry from "../src/mcp/McpSessionRegistry.ts";
import * as McpToolAccess from "../src/mcp/McpToolAccess.ts";
import * as McpToolAccessTestkit from "../src/mcp/McpToolAccess.testkit.ts";
import * as ServerSettings from "../src/serverSettings.ts";

const token = "probe";
const code = "plum-4471";

const scope: McpInvocationContext.McpThreadInvocationScope = {
environmentId: EnvironmentId.make("probe"),
requestNamespace: token,
thread: {
threadId: ThreadId.make("probe-thread"),
providerSessionId: token,
providerInstanceId: ProviderInstanceId.make("probe"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};

const ProbeToolkit = Toolkit.make(
Tool.make("delegate_task", {
description: "Not part of this probe. Do not call.",
success: Schema.Struct({}),
failure: OrchestratorMcpFailure,
failureMode: "return",
}),
Tool.make("probe_secret", {
description: "Returns the probe's secret code.",
success: Schema.Struct({ code: Schema.String }),
failure: OrchestratorMcpFailure,
failureMode: "return",
})
// Read-only, so a harness in a no-approval mode still runs it.
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false),
);

const served = McpHttpServer.layerMcpTransport(
Layer.mergeAll(
McpHttpServer.toolkitRegistration(
ProbeToolkit,
McpToolAccess.toLayer(ProbeToolkit, {
delegate_task: McpToolAccess.reads(() => Effect.succeed({})),
probe_secret: McpToolAccess.reads(() =>
Effect.log("probe: the model called the hidden tool").pipe(Effect.as({ code })),
),
}),
),
McpHttpServer.layerToolSearch,
),
).pipe(
Layer.provide(ServerSettings.layerTest()),
Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
Layer.provide(
Layer.mock(McpSessionRegistry.McpSessionRegistry)({
resolve: (candidate) => Effect.succeed(candidate === token ? scope : undefined),
}),
),
);

const command = Command.make(
"mcp-relist-probe",
{ port: Flag.Int("port").pipe(Flag.withDefault(8787)) },
({ port }) =>
Console.log(`MCP endpoint: http://127.0.0.1:${port}/mcp
Headers: "Authorization: Bearer ${token}" and "t3-tool-exposure: deferred"
Prompt: Find the tool that returns the probe's secret code, call it, and reply with the code.
Pass: a "mcp.tool-search.relisted" line, then "the model called the hidden tool" in one turn.
Restart this server for each run: a search stays loaded for the life of the process.
`).pipe(
Effect.andThen(
HttpRouter.serve(served, { disableListenLog: true }).pipe(
Layer.provide(NodeHttpServer.layer(NodeHttp.createServer, { port, host: "127.0.0.1" })),
Layer.provide(Logger.layer([Logger.consolePretty()])),
Layer.provide(Layer.succeed(References.MinimumLogLevel, "Debug")),
Layer.launch,
),
),
),
);

if (import.meta.main) {
Command.run(command, { version: "0.0.0" }).pipe(
Effect.provide(NodeServices.layer),
NodeRuntime.runMain,
);
}
19 changes: 17 additions & 2 deletions apps/server/src/mcp/McpHttpServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import * as ServerSettings from "../serverSettings.ts";
import { advertisedJsonSchema } from "./advertisedJsonSchema.ts";
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpToolAccess from "./McpToolAccess.ts";
import * as McpToolExposure from "./McpToolExposure.ts";
import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
Expand Down Expand Up @@ -2149,6 +2150,7 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
tool("delegate_task", "Delegates a task."),
tool("preview_open", "Opens a browser preview."),
tool("schedule_task", "Schedules a task."),
tool("t3_theme_set", "Restyles T3 Code.").annotate(McpToolExposure.Pack, "customization"),
);
const reads = McpToolAccess.reads(() => Effect.succeed({}));
const serverLayer = McpHttpServer.layerMcpTransport(
Expand All @@ -2159,6 +2161,7 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
delegate_task: reads,
preview_open: reads,
schedule_task: reads,
t3_theme_set: reads,
}),
),
McpHttpServer.layerToolSearch,
Expand Down Expand Up @@ -2232,15 +2235,27 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
const deferring = yield* session("deferringToken", true);
const other = yield* session("otherToken", false);
expect(yield* deferring.listed).toEqual(["delegate_task", "tool_search"]);
expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);
const everything = ["delegate_task", "preview_open", "schedule_task", "t3_theme_set"];
expect(yield* other.listed).toEqual(everything);
// Unlisted tools stay callable.
expect((yield* deferring.call("schedule_task", {})).structuredContent).toEqual({});

expect(
(yield* deferring.call("tool_search", { query: "browser" })).structuredContent,
).toEqual({ tools: [{ name: "preview_open", description: "Opens a browser preview." }] });
expect(yield* deferring.listed).toEqual(["delegate_task", "preview_open", "tool_search"]);
expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);
expect(yield* other.listed).toEqual(everything);

// A pack's name loads its tools, whatever their text says.
expect(
(yield* deferring.call("tool_search", { query: "customization" })).structuredContent,
).toEqual({ tools: [{ name: "t3_theme_set", description: "Restyles T3 Code." }] });
expect(yield* deferring.listed).toEqual([
"delegate_task",
"preview_open",
"t3_theme_set",
"tool_search",
]);
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
9 changes: 8 additions & 1 deletion apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1540,7 +1540,11 @@ const layerToolExposure = Layer.effect(
enabledWhen === undefined || enabledWhen({ protocolVersion: "", capabilities: {} })
);
})
.map(({ tool }) => ({ name: tool.name, description: tool.description ?? "" })),
.map(({ tool, annotations }) => ({
name: tool.name,
description: tool.description ?? "",
pack: Context.getOrUndefined(annotations, McpToolExposure.Pack),
})),
() => server.notifications["notifications/tools/list_changed"]({}),
);
}),
Expand All @@ -1562,6 +1566,9 @@ const layerDeferredListing = McpServer.visibility(
if (headers[MCP_TOOL_EXPOSURE_HEADER] !== "deferred" || providerSessionId === undefined) {
return target !== McpToolExposure.TOOL_SEARCH;
}
if (exposure.relisted(providerSessionId)) {
yield* Effect.logDebug("mcp.tool-search.relisted", { providerSessionId });
}
return exposure.isListed(providerSessionId, target);
});
}),
Expand Down
63 changes: 54 additions & 9 deletions apps/server/src/mcp/McpToolExposure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,41 @@ const MAX_RESULTS = 10;
// Sessions that ended are never reported here, so keep only the newest.
const MAX_SESSIONS = 256;

/**
* Tools for a job few threads do. `tool_search` with the pack's name loads all of
* them, and they stay outside the gated tool budget (AgentContextBudget.test.ts).
*/
export const PACKS = {
customization: "restyle T3 Code itself",
} as const;

export type PackName = keyof typeof PACKS;

/** Tool annotation that puts a tool in a pack. */
export class Pack extends Context.Service<Pack, PackName>()("t3/mcp/McpToolExposure/Pack") {}

export interface ListedTool {
readonly name: string;
readonly description: string;
readonly pack?: PackName | undefined;
}

export interface ToolSearchCaller {
readonly providerSessionId: string;
readonly providerInstanceId: string;
}

export class McpToolExposure extends Context.Service<
McpToolExposure,
{
/** Finds tools for the query and lists them to the session from now on. */
readonly search: (
providerSessionId: string,
caller: ToolSearchCaller,
query: string,
) => Effect.Effect<ReadonlyArray<ListedTool>>;
readonly isListed: (providerSessionId: string, tool: string) => boolean;
/** True once, when the session lists tools for the first time after a search loaded some. */
readonly relisted: (providerSessionId: string) => boolean;
}
>()("t3/mcp/McpToolExposure") {}

Expand Down Expand Up @@ -57,31 +78,55 @@ export const make = (
for (const oldest of loaded.keys()) {
if (loaded.size <= MAX_SESSIONS) break;
loaded.delete(oldest);
awaitingRelist.delete(oldest);
relisters.delete(oldest);
}
};
// Sessions whose last search loaded tools and that have not listed tools since.
const awaitingRelist = new Set<string>();
// A harness that lists lazily can search twice before it lists, so only warn about
// sessions that have never listed after a search.
const relisters = new Set<string>();
return McpToolExposure.of({
search: Effect.fn("McpToolExposure.search")(function* (providerSessionId, query) {
search: Effect.fn("McpToolExposure.search")(function* (caller, query) {
const { providerSessionId } = caller;
const terms = query
.toLowerCase()
.split(/[^a-z0-9_]+/u)
.filter(Boolean);
const found = tools()
.filter((tool) => tool.name !== TOOL_SEARCH)
.map((tool) => ({ tool, score: score(tool, terms) }))
.filter((match) => match.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, MAX_RESULTS)
.map((match) => match.tool);
const candidates = tools().filter((tool) => tool.name !== TOOL_SEARCH);
const inNamedPack = (tool: ListedTool) =>
tool.pack !== undefined && terms.includes(tool.pack);
const found = [
...candidates.filter(inNamedPack),
...candidates
.filter((tool) => !inNamedPack(tool))
.map((tool) => ({ tool, score: score(tool, terms) }))
.filter((match) => match.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, MAX_RESULTS)
.map((match) => match.tool),
];
if (awaitingRelist.has(providerSessionId) && !relisters.has(providerSessionId)) {
// The harness ignored list_changed, so its model cannot see what the search loads.
yield* Effect.logWarning("mcp.tool-search.not-relisted", caller);
}
if (found.length > 0) {
load(
providerSessionId,
found.map((tool) => tool.name),
);
awaitingRelist.add(providerSessionId);
yield* announceListChanged();
}
return found;
}),
isListed: (providerSessionId, tool) =>
DIRECT_TOOLS.has(tool) || loaded.get(providerSessionId)?.has(tool) === true,
relisted: (providerSessionId) => {
if (!awaitingRelist.delete(providerSessionId)) return false;
relisters.add(providerSessionId);
return true;
},
});
};
8 changes: 6 additions & 2 deletions apps/server/src/mcp/toolkits/theme/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import * as Schema from "effect/Schema";
import { Tool, Toolkit } from "effect/ai";
import * as EnvironmentTheme from "../../../environmentTheme.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolExposure from "../../McpToolExposure.ts";
import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts";
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";

Expand Down Expand Up @@ -50,7 +51,8 @@ const ThemeReadTool = Tool.make("t3_theme_read", {
}),
})
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false);
.annotate(Tool.Destructive, false)
.annotate(McpToolExposure.Pack, "customization");

const ThemeSetTool = Tool.make("t3_theme_set", {
...shared,
Expand All @@ -66,6 +68,8 @@ const ThemeSetTool = Tool.make("t3_theme_set", {
appearance: Schema.optionalKey(Appearance),
published: Schema.Boolean,
}),
}).annotate(Tool.Destructive, true);
})
.annotate(Tool.Destructive, true)
.annotate(McpToolExposure.Pack, "customization");

export const ThemeToolkit = Toolkit.make(ThemeReadTool, ThemeSetTool);
9 changes: 8 additions & 1 deletion apps/server/src/mcp/toolkits/toolSearch/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,14 @@ export const layer = McpToolAccess.toLayer(ToolSearchToolkit, {
Effect.flatMap((scope) => McpInvocationContext.requireThreadScope(scope, "tool_search")),
);
const exposure = yield* McpToolExposure.McpToolExposure;
return { tools: yield* exposure.search(thread.providerSessionId, query) };
const found = yield* exposure.search(
{
providerSessionId: thread.providerSessionId,
providerInstanceId: thread.providerInstanceId,
},
query,
);
return { tools: found.map(({ name, description }) => ({ name, description })) };
}),
),
});
7 changes: 5 additions & 2 deletions apps/server/src/mcp/toolkits/toolSearch/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ import { McpSchema, Tool, Toolkit } from "effect/ai";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolExposure from "../../McpToolExposure.ts";

const packList = Object.entries(McpToolExposure.PACKS)
.map(([name, purpose]) => `\`${name}\` (${purpose})`)
.join(", ");

const ToolSearchTool = Tool.make(McpToolExposure.TOOL_SEARCH, {
description:
"Load T3 Code tools you do not have yet, then call them by name. Search by name or purpose: threads (t3_thread_*), projects (t3_project_*), worktrees, preview_* browser, device_*, html_preview/html_render, schedule_task, pull requests and guides, attachments, request_secret, environment links. Exact names work too.",
description: `Load T3 Code tools you do not have yet, then call them by name. Search by name or purpose: threads (t3_thread_*), projects (t3_project_*), worktrees, preview_* browser, device_*, html_preview/html_render, schedule_task, pull requests and guides, attachments, request_secret, environment links. Exact names work too. A pack name loads its whole set: ${packList}.`,
parameters: Schema.Struct({ query: Schema.String.check(Schema.isMaxLength(500)) }),
success: Schema.Struct({
tools: Schema.Array(Schema.Struct({ name: Schema.String, description: Schema.String })),
Expand Down
Loading
Loading