Skip to content
Closed
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
28 changes: 28 additions & 0 deletions apps/server/src/mcp/AcpMcpStdioBridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -445,4 +445,32 @@ describe("AcpMcpStdioBridge", () => {
expect(signal?.aborted).toBe(true);
}),
);

it.effect("forwards t3-tool-exposure when toolExposure is configured on the stdio bridge", () =>
Effect.gen(function* () {
const headersSeen: Array<string | null> = [];
const input = new NodeStream.PassThrough();
const written: Array<string> = [];
const bridge = runAcpMcpStdioBridge({
endpoint: "http://127.0.0.1:1/mcp",
authorization: "Bearer bridge-test",
toolExposure: "deferred",
input,
output: {
write: (chunk: string) => {
written.push(chunk);
},
},
fetchImplementation: async (_url, init) => {
const request = new Request("http://127.0.0.1:1/mcp", init);
headersSeen.push(request.headers.get("t3-tool-exposure"));
return Response.json({ jsonrpc: "2.0", id: 1, result: { tools: [] } });
},
});
input.end(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })}\n`);
yield* bridge;
expect(headersSeen).toEqual(["deferred"]);
expect(written).toHaveLength(1);
}),
);
});
6 changes: 6 additions & 0 deletions apps/server/src/mcp/AcpMcpStdioBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const MCP_PROTOCOL_VERSION = "2025-06-18";
export interface AcpMcpStdioBridgeOptions {
readonly endpoint: string;
readonly authorization: string;
readonly toolExposure?: string | undefined;
readonly input: NodeJS.ReadableStream;
readonly output: { write(chunk: string): unknown };
readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
Expand Down Expand Up @@ -236,6 +237,9 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
"content-type": "application/json",
accept: "application/json, text/event-stream",
authorization: options.authorization,
...(options.toolExposure === undefined
? {}
: { "t3-tool-exposure": options.toolExposure }),
...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
},
Expand Down Expand Up @@ -349,6 +353,7 @@ export async function runAcpMcpCliFastPath(
): Promise<void> {
const endpoint = process.env.T3_ACP_MCP_ENDPOINT;
const authorization = process.env.T3_ACP_MCP_AUTHORIZATION;
const toolExposure = process.env.T3_ACP_MCP_TOOL_EXPOSURE?.trim();
if (endpoint === undefined || authorization === undefined) {
process.stderr.write(`${command} requires T3_ACP_MCP_ENDPOINT and T3_ACP_MCP_AUTHORIZATION.\n`);
process.exitCode = 2;
Expand All @@ -359,6 +364,7 @@ export async function runAcpMcpCliFastPath(
runAcpMcpStdioBridge({
endpoint,
authorization,
...(toolExposure ? { toolExposure } : {}),
input: process.stdin,
output: process.stdout,
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1584,7 +1584,7 @@ describe("AcpRegistryAdapterV2", () => {
],
},
];
const stdio = (authorization: string) => [
const stdio = (authorization: string, deferred = false) => [
{
name: "t3-code",
command: selfInvocation.command,
Expand All @@ -1593,6 +1593,7 @@ describe("AcpRegistryAdapterV2", () => {
{ name: "ELECTRON_RUN_AS_NODE", value: "1" },
{ name: "T3_ACP_MCP_ENDPOINT", value: endpoint },
{ name: "T3_ACP_MCP_AUTHORIZATION", value: authorization },
...(deferred ? [{ name: "T3_ACP_MCP_TOOL_EXPOSURE", value: "deferred" }] : []),
],
},
];
Expand All @@ -1610,8 +1611,8 @@ describe("AcpRegistryAdapterV2", () => {
{ new: acp, load: acp },
);
assert.deepEqual(yield* sessionMcpServers({ agentId: "github-copilot-cli" }), {
new: stdio("Bearer opened-token"),
load: stdio("Bearer rotated-token"),
new: stdio("Bearer opened-token", true),
load: stdio("Bearer rotated-token", true),
});
assert.deepEqual(yield* sessionMcpServers({ agentId: "gemini" }, { T3_ACP_MCP_HTTP: "1" }), {
new: stdio("Bearer opened-token"),
Expand Down
205 changes: 205 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { NodeHttpServer } from "@effect/platform-node";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import {
ChatFileAttachment,
EnvironmentId,
MessageId,
NodeId,
OrchestratorMcpFailure,
ProjectId,
ProviderInstanceId,
ProviderSessionId,
Expand All @@ -25,7 +28,10 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { Tool, Toolkit } from "effect/ai";
import { HttpBody, HttpClient, HttpRouter } from "effect/http";
import { ChildProcessSpawner } from "effect/process";
import * as TestClock from "effect/testing/TestClock";
import type * as EffectAcpSchema from "effect-acp/compat";
Expand All @@ -35,6 +41,12 @@ import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
import * as McpHttpServer from "../../mcp/McpHttpServer.ts";
import * as McpInvocationContext from "../../mcp/McpInvocationContext.ts";
import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts";
import * as McpToolAccess from "../../mcp/McpToolAccess.ts";
import * as McpToolAccessTestkit from "../../mcp/McpToolAccess.testkit.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts";
import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts";
import { ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE } from "../../provider/antigravityAuthSupport.ts";
Expand Down Expand Up @@ -316,6 +328,199 @@ describe("AntigravityAdapterV2 harness recovery", () => {
);
});

describe("AntigravityAdapterV2 MCP exposure", () => {
it.live(
"configures deferred HTTP MCP exposure through the shared adapter so optional T3 tools stay callable via tool_search",
() =>
Effect.scoped(
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const crypto = yield* SecureRandom.SecureRandom;
const mockAgentPath = yield* path.fromFileUrl(
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
);
const instanceId = ProviderInstanceId.make("antigravity-mcp-exposure-test");
const threadId = ThreadId.make("thread-antigravity-mcp-exposure");
const providerSessionId = ProviderSessionId.make("provider-session-mcp-exposure");
const token = "antigravity-exposure-token";
const capturedMcpServers = yield* Deferred.make<{
readonly stdio: ReadonlyArray<EffectAcpSchema.McpServer>;
readonly http: ReadonlyArray<EffectAcpSchema.McpServer>;
}>();

const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
yield* mcpSessions.set({
environmentId: EnvironmentId.make("env-1"),
threadId,
providerSessionId,
providerInstanceId: instanceId,
endpoint: "http://127.0.0.1:3773/mcp",
authorizationHeader: `Bearer ${token}`,
browserToolsAvailable: true,
});

const adapter = yield* makeAntigravityAdapterV2({
instanceId,
selfInvocation: yield* resolveSelfInvocation(),
makeRuntime: (input) =>
Deferred.succeed(capturedMcpServers, {
stdio: input.mcpServers ?? [],
http: input.httpMcpServers ?? [],
}).pipe(
Effect.andThen(
makeAntigravityAcpRuntime({
...input,
childProcessSpawner,
spawn: {
command: process.execPath,
args: [mockAgentPath],
cwd: input.cwd,
env: { T3_ACP_ANTIGRAVITY: "1", T3_ACP_MCP_HTTP: "1" },
},
}),
),
Effect.provideService(SecureRandom.SecureRandom, crypto),
),
withProcess: (_stop, task) => task,
defaultModel: Effect.undefined,
});

yield* adapter.openSession({
threadId,
providerSessionId,
modelSelection: { instanceId, model: "gemini-test-low" },
runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: process.cwd(),
}),
});

const mcpServers = yield* Deferred.await(capturedMcpServers);
const stdioT3Server = mcpServers.stdio.find(
(server): server is Extract<EffectAcpSchema.McpServer, { command: string }> =>
"command" in server && server.name === "t3-code",
);
assert.isDefined(stdioT3Server);
assert.strictEqual(
stdioT3Server?.env?.find((entry) => entry.name === "T3_ACP_MCP_TOOL_EXPOSURE")?.value,
"deferred",
);

const t3Server = mcpServers.http.find(
(server): server is Extract<EffectAcpSchema.McpServer, { type: "http" }> =>
"type" in server && server.type === "http" && server.name === "t3-code",
);
assert.isDefined(t3Server);

const scope: McpInvocationContext.McpThreadInvocationScope = {
environmentId: EnvironmentId.make("env-1"),
requestNamespace: token,
thread: {
threadId,
providerSessionId,
providerInstanceId: instanceId,
},
client: undefined,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
};
const tool = (name: string, description: string) =>
Tool.make(name, {
description,
success: Schema.Struct({}),
failure: OrchestratorMcpFailure,
failureMode: "return",
});
const OptionalToolkit = Toolkit.make(
tool("delegate_task", "Delegates a task."),
tool("preview_open", "Opens a browser preview."),
tool("schedule_task", "Schedules a task."),
);
const reads = McpToolAccess.reads(() => Effect.succeed({}));
const serverLayer = McpHttpServer.layerMcpTransport(
Layer.mergeAll(
McpHttpServer.toolkitRegistration(
OptionalToolkit,
McpToolAccess.toLayer(OptionalToolkit, {
delegate_task: reads,
preview_open: reads,
schedule_task: reads,
}),
),
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),
}),
),
);
yield* HttpRouter.serve(serverLayer, {
disableListenLog: true,
disableLogger: true,
}).pipe(Layer.build);

const httpClient = yield* HttpClient.HttpClient;
const headers: Record<string, string> = {
accept: "application/json, text/event-stream",
...Object.fromEntries(
(t3Server?.headers ?? []).map((header) => [header.name.toLowerCase(), header.value]),
),
};
const initialize = yield* httpClient.post("/mcp", {
headers,
body: HttpBody.text(
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"antigravity-probe","version":"1.0.0"}}}`,
"application/json",
),
});
const rpc = (method: string, params: object) =>
httpClient
.post("/mcp", {
headers: {
...headers,
"mcp-session-id": initialize.headers["mcp-session-id"]!,
"mcp-protocol-version": "2025-06-18",
},
body: HttpBody.text(
JSON.stringify({ jsonrpc: "2.0", id: 2, method, params }),
"application/json",
),
})
.pipe(
Effect.flatMap((response) => response.text),
Effect.map((text): unknown =>
text
.split("\n")
.filter((line) => line.startsWith("data: ") || line.startsWith("{"))
.map((line) => JSON.parse(line.replace(/^data: /u, "")) as { id?: number })
.find((message) => message.id === 2),
),
);

const listed = yield* rpc("tools/list", {}).pipe(
Effect.map((body) =>
(body as { result: { tools: ReadonlyArray<{ name: string }> } }).result.tools
.map((listedTool) => listedTool.name)
.sort(),
),
);
assert.deepEqual(listed, ["delegate_task", "tool_search"]);

const scheduled = yield* rpc("tools/call", { name: "schedule_task", arguments: {} }).pipe(
Effect.map((body) => (body as { result: { structuredContent?: unknown } }).result),
);
assert.deepEqual(scheduled.structuredContent, {});
}).pipe(Effect.provide(layerSession), Effect.provide(NodeHttpServer.layerTest)),
),
);
});

describe("AntigravityAdapterV2 compaction", () => {
it.live.each([false, true])(
"negotiates native goals (%s) without enabling manual compaction",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ export function makeAntigravityAcpAdapterFlavor(
supportsNativeGoals: options.supportsNativeGoals ?? Effect.succeed(false),
// Agents that advertise HTTP MCP skip the stdio bridge process; others keep stdio.
mcpOverHttp: true,
deferMcpTools: true,
sessionCarriesPullRequestLinking: antigravityAppendsSystemPrompt,
makeRuntime,
buildAttachmentPrompt: ({
Expand Down
Loading
Loading