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
8 changes: 8 additions & 0 deletions apps/server/src/mcp/McpToolAccess.testkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@ export const liveThreadsLayer = Layer.mock(ThreadManagement.ThreadManagementServ
getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)),
});

/** One host's threads: a thread it does not hold reads as absent, as the real service does. */
export const hostThreadsLayer = (
threads: (threadId: ThreadId) => OrchestrationV2ThreadShell | null,
) =>
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: (threadId) => Effect.succeed(threads(threadId)),
});

export const idleThreadProjection = (
shell: OrchestrationV2ThreadShell,
): OrchestrationV2ThreadProjection => {
Expand Down
305 changes: 304 additions & 1 deletion apps/server/src/mcp/toolkits/issues/handlers.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import {
EnvironmentId,
IssueTrackerKind,
OrchestratorMcpFailure,
ProjectId,
ProviderInstanceId,
RunId,
ThreadId,
type IssueDetail,
type OrchestrationProjectShell,
Expand All @@ -14,21 +16,25 @@ import {
IssueTrackerError,
type StandaloneIssueTrackerApi,
} from "@t3tools/source-control-core/server/IssueTracker";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import type { Tool } from "effect/ai";
import { McpSchema, McpServer, type Tool } from "effect/ai";

import * as IssueService from "../../../issue/IssueService.ts";
import * as IssueTrackerRegistry from "../../../issue/IssueTrackerRegistry.ts";
import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
import * as ThreadIssueService from "../../../orchestration-v2/ThreadIssueService.ts";
import { v2PullRequestThread } from "../../../orchestration-v2/testkit/pullRequestFixtures.ts";
import * as IssueTrackerBindings from "../../../persistence/IssueTrackerBindings.ts";
import * as ProjectService from "../../../project/ProjectService.ts";
import * as RepositoryIdentityResolver from "../../../project/RepositoryIdentityResolver.ts";
import * as McpHttpServer from "../../McpHttpServer.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
Expand All @@ -39,6 +45,19 @@ const PROJECT_ID = ProjectId.make("project-1");
const THREAD_ID = ThreadId.make("thread-1");
const GITHUB = IssueTrackerKind.make("github");

const mcpClient = McpSchema.McpServerClient.of({
clientId: 1,
protocolVersion: "2025-06-18",
clientCapabilities: {},
clientInfo: { name: "mcp-test", version: "1" },
initializePayload: {
protocolVersion: "2025-06-18",
capabilities: {},
clientInfo: { name: "mcp-test", version: "1" },
},
getClient: Effect.die("unused"),
});

const invocation = (
capabilities: ReadonlyArray<McpInvocationContext.McpCapability>,
): McpInvocationContext.McpInvocationScope => ({
Expand Down Expand Up @@ -442,4 +461,288 @@ describe("issue toolkit handlers", () => {
expect(unlinked.wasLinked).toBe(true);
}),
);

// A named environment is another machine: the call is checked here and run there, and the link
// is stored on the thread that machine holds. The client shows it from that thread's shell.
it.effect(
"links an issue on a linked host, repeats as already linked, and shows it on that host's thread",
() => {
const here = EnvironmentId.make("environment-here");
const box = EnvironmentId.make("environment-box");
const air = EnvironmentId.make("environment-air");
// Each host keeps the threads it owns. The caller's host has none of the remote thread.
const threadsByHost = new Map<string, ReadonlyArray<ThreadIssueLink>>([
[here, []],
[box, []],
[air, []],
]);
const stored = (host: string) => threadsByHost.get(host) ?? [];
const remember = (host: string, link: ThreadIssueLink) =>
threadsByHost.set(host, [...stored(host), link]);
const forget = (host: string, key: string) => {
const held = stored(host);
threadsByHost.set(
host,
held.filter((link) => link.key !== key),
);
return held.some((link) => link.key === key);
};
// The in-process server puts the call's host on the fiber before the handler runs, the way
// the auth middleware does for an HTTP request. The store reads it from there.
const callerHost = () =>
Context.getOrUndefined(
Fiber.getCurrent()!.context,
McpInvocationContext.McpInvocationContext,
)!.environmentId;
// The tracker and the thread store, shared so each host reads and writes its own rows.
const services = Layer.mergeAll(
projectLayer,
Layer.mock(Orchestrator.OrchestratorV2)({
getThreadShell: (id) =>
Effect.succeed(id === THREAD_ID ? makeThread(stored(callerHost())) : null),
}),
Layer.mock(IssueService.IssueService)({
detail: () => Effect.succeed(detail),
linkMetadata: () => Effect.succeed(detail),
projectScope: (projectId) =>
Effect.succeed({
projectId,
tracker: GITHUB,
host: "github.com",
scope: "t3tools/t3code",
}),
resolveUrl: (url) =>
Effect.succeed({
projectId: PROJECT_ID,
tracker: GITHUB,
host: "github.com",
scope: "t3tools/t3code",
key: url.split("/").at(-1)!,
writable: true,
}),
}),
Layer.mock(ThreadIssueService.ThreadIssueService)({
link: (input) => {
const host = callerHost();
const alreadyLinked = stored(host).some((link) => link.key === input.ref.key);
if (!alreadyLinked) {
remember(host, {
tracker: input.ref.tracker,
host: input.ref.host,
scope: input.ref.scope,
key: input.ref.key,
projectId: input.ref.projectId,
url: input.url,
displayKey: input.displayKey,
title: input.title,
source: input.source,
linkedAt: "2026-08-10T00:00:00.000Z",
});
}
return Effect.succeed({ alreadyLinked });
},
unlink: (input) => Effect.succeed({ wasLinked: forget(callerHost(), input.key.key) }),
}),
);
const hosts = McpHttpServer.toolkitRegistration(IssuesToolkit, IssuesHandlers.layer).pipe(
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provide(
Layer.mergeAll(
services,
McpToolAccessTestkit.hostThreadsLayer((threadId) =>
threadId === THREAD_ID
? {
...makeThread(stored(here)),
activeRunId: RunId.make("run-1"),
providerInstanceId: ProviderInstanceId.make("codex"),
}
: null,
),
),
),
// The other machine runs the same tools against its own threads. A built copy of the
// registration is that machine: its server checks the thread and stores the link there.
Layer.provide(
Layer.effect(
PeerForwarding.PeerForwarding,
Effect.gen(function* () {
const there = yield* Layer.build(
McpHttpServer.toolkitRegistration(IssuesToolkit, IssuesHandlers.layer).pipe(
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provide(
Layer.mergeAll(
services,
McpToolAccessTestkit.hostThreadsLayer((threadId) =>
threadId === THREAD_ID ? makeThread(stored(callerHost())) : null,
),
),
),
),
);
const remote = Context.get(there, McpServer.McpServer);
return PeerForwarding.PeerForwarding.of({
// Only call is reached: the three issue tools forward through it.
...({} as PeerForwarding.PeerForwarding["Service"]),
call: (scope, tool, environmentId, params) =>
remote
.callTool({
name: tool.name,
arguments: params as Record<string, unknown>,
})
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, {
...scope,
environmentId,
}),
Effect.provideService(McpSchema.McpServerClient, mcpClient),
// A refused call comes back as text, the way the remote server sends it.
Effect.flatMap((result) =>
result.isError
? Effect.fail(
new OrchestratorMcpFailure({
code: "orchestration_error",
message:
result.content.find((part) => part.type === "text")?.text ??
"The linked host refused.",
}),
)
: Effect.succeed(result.structuredContent as never),
),
Effect.mapError(
(error) =>
new OrchestratorMcpFailure({
code: "orchestration_error",
message: error.message,
}),
),
),
});
}),
),
),
);
return Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const caller: McpInvocationContext.McpInvocationScope = {
...invocation(["issues"]),
environmentId: here,
};
const link = (environmentId: string, threadId: string) =>
server
.callTool({
name: "link_issue",
arguments: { environmentId, threadId, url: detail.url },
})
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, caller),
Effect.provideService(McpSchema.McpServerClient, mcpClient),
);
const first = yield* link(box, THREAD_ID);
expect(first.isError).toBeFalsy();
expect(first.structuredContent).toMatchObject({
key: "7",
url: detail.url,
alreadyLinked: false,
});
// The link is stored on the host that owns the thread, not on the caller.
expect(stored(box)).toMatchObject([{ key: "7", title: "Seven", url: detail.url }]);
expect(stored(air)).toEqual([]);
const again = yield* link(box, THREAD_ID);
expect(again.structuredContent).toMatchObject({ alreadyLinked: true });
expect(stored(box)).toHaveLength(1);
// A thread the target host does not have is refused there, not stored here.
const missing = yield* link(box, "thread-missing");
expect(missing.isError).toBe(true);
expect(missing.content).toEqual([
{ type: "text", text: "Thread thread-missing was not found." },
]);
// A second linked host holds the thread too, and stores its own link.
const elsewhere = yield* link(air, THREAD_ID);
expect(elsewhere.isError).toBeFalsy();
expect(elsewhere.structuredContent).toMatchObject({ alreadyLinked: false });
expect(stored(air)).toMatchObject([{ key: "7", url: detail.url }]);
expect(stored(box)).toHaveLength(1);
// Omitting the environment keeps the link on this host.
const local = yield* server
.callTool({ name: "link_issue", arguments: { url: detail.url } })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, caller),
Effect.provideService(McpSchema.McpServerClient, mcpClient),
);
expect(local.isError).toBeFalsy();
expect(stored(box)).toHaveLength(1);
// The host that holds the thread lists it, and unlinking there removes only its own.
const listed = yield* server
.callTool({
name: "list_thread_issues",
arguments: { environmentId: box, threadId: THREAD_ID },
})
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, caller),
Effect.provideService(McpSchema.McpServerClient, mcpClient),
);
expect(listed.structuredContent).toMatchObject({
issues: [{ key: "7", title: "Seven", url: detail.url }],
});
const removed = yield* server
.callTool({
name: "unlink_issue",
arguments: { environmentId: box, threadId: THREAD_ID, url: detail.url },
})
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, caller),
Effect.provideService(McpSchema.McpServerClient, mcpClient),
);
expect(removed.structuredContent).toMatchObject({ key: "7", wasLinked: true });
expect(stored(box)).toEqual([]);
expect(stored(air)).toHaveLength(1);
}).pipe(Effect.provide(hosts));
},
);

// No peer service is a machine that cannot reach its linked environments.
it.effect("refuses a linked host when this machine cannot reach one", () => {
const unreachable = McpHttpServer.toolkitRegistration(IssuesToolkit, IssuesHandlers.layer).pipe(
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provide(
Layer.mergeAll(
projectLayer,
Layer.mock(Orchestrator.OrchestratorV2)({
getThreadShell: (id) => Effect.succeed(id === THREAD_ID ? makeThread([]) : null),
}),
Layer.mock(IssueService.IssueService)({}),
Layer.mock(ThreadIssueService.ThreadIssueService)({}),
McpToolAccessTestkit.hostThreadsLayer((threadId) =>
threadId === THREAD_ID
? {
...makeThread([]),
activeRunId: RunId.make("run-1"),
providerInstanceId: ProviderInstanceId.make("codex"),
}
: null,
),
),
),
);
return Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const refused = yield* server
.callTool({
name: "link_issue",
arguments: {
environmentId: "environment-away",
threadId: THREAD_ID,
url: detail.url,
},
})
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(["issues"])),
Effect.provideService(McpSchema.McpServerClient, mcpClient),
);
expect(refused.isError).toBe(true);
expect(refused.content).toEqual([
{ type: "text", text: "This environment cannot reach linked environments." },
]);
}).pipe(Effect.provide(unreachable));
});
});
Loading
Loading