Skip to content
Merged
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
13 changes: 12 additions & 1 deletion apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ import packageJson from "../../package.json" with { type: "json" };
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
import * as ChatManager from "./toolkits/chat/ChatManager.ts";
import { ChatToolkitHandlersLive } from "./toolkits/chat/handlers.ts";
import { ChatToolkit } from "./toolkits/chat/tools.ts";
import {
PreviewSnapshotToolkitHandlersLive,
PreviewStandardToolkitHandlersLive,
Expand Down Expand Up @@ -208,10 +211,18 @@ export const PreviewToolkitRegistrationLive = Layer.mergeAll(
PreviewSnapshotRegistrationLive,
);

export const ChatToolkitRegistrationLive = McpServer.toolkit(ChatToolkit).pipe(
Layer.provide(ChatToolkitHandlersLive),
Layer.provide(ChatManager.layer),
);

const McpTransportLive = McpServer.layerHttp({
name: "T3 Code",
version: packageJson.version,
path: "/mcp",
}).pipe(Layer.provide(McpAuthMiddlewareLive));

export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
export const layer = Layer.mergeAll(
PreviewToolkitRegistrationLive,
ChatToolkitRegistrationLive,
).pipe(Layer.provideMerge(McpTransportLive));
4 changes: 2 additions & 2 deletions apps/server/src/mcp/McpInvocationContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";

export type McpCapability = "preview";
export type McpCapability = "chat" | "preview";

export interface McpInvocationScope {
readonly environmentId: EnvironmentId;
Expand All @@ -25,7 +25,7 @@ export class McpInvocationContext extends Context.Service<
>()("t3/mcp/McpInvocationContext") {}

export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function* (
capability: McpCapability,
capability: "preview",
) {
const invocation = yield* McpInvocationContext;
if (!invocation.capabilities.has(capability)) {
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/mcp/McpSessionRegistry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t

const resolved = yield* registry.resolve(token);
expect(resolved?.threadId).toBe(threadId);
expect(resolved?.capabilities).toEqual(new Set(["chat", "preview"]));

yield* registry.revokeThread(threadId);
expect(yield* registry.resolve(token)).toBeUndefined();
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/mcp/McpSessionRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
threadId: ThreadId.make(request.threadId),
providerSessionId,
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
capabilities: new Set(["preview"]),
capabilities: new Set(["chat", "preview"]),
issuedAt,
expiresAt,
};
Expand Down
270 changes: 270 additions & 0 deletions apps/server/src/mcp/toolkits/chat/ChatManager.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
type OrchestrationCommand,
type OrchestrationProjectShell,
type OrchestrationShellSnapshot,
type OrchestrationThread,
type OrchestrationThreadShell,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";

import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../../../orchestration/Services/OrchestrationEngine.ts";
import {
ProjectionSnapshotQuery,
type ProjectionSnapshotQueryShape,
} from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
import type { McpInvocationScope } from "../../McpInvocationContext.ts";
import { ChatManager, deriveSpawnedChatTitle, layer } from "./ChatManager.ts";

const now = "2026-07-20T12:00:00.000Z";
const environmentId = EnvironmentId.make("environment-chat-manager-test");
const projectId = ProjectId.make("project-chat-manager-test");
const currentThreadId = ThreadId.make("thread-current");
const modelSelection = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
};

const project = {
id: projectId,
title: "T3 Code",
workspaceRoot: "/workspace/t3",
repositoryIdentity: null,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("claude"),
model: "claude-sonnet-4-5",
},
scripts: [],
createdAt: now,
updatedAt: now,
} satisfies OrchestrationProjectShell;

const currentShell = {
id: currentThreadId,
projectId,
title: "Parent chat",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/chat-tools",
worktreePath: "/workspace/t3-worktree",
latestTurn: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
} satisfies OrchestrationThreadShell;

const currentDetail = {
id: currentThreadId,
projectId,
title: currentShell.title,
modelSelection,
runtimeMode: currentShell.runtimeMode,
interactionMode: currentShell.interactionMode,
branch: currentShell.branch,
worktreePath: currentShell.worktreePath,
latestTurn: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
} satisfies OrchestrationThread;

const invocation: McpInvocationScope = {
environmentId,
threadId: currentThreadId,
providerSessionId: "provider-session-chat-manager-test",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(["chat", "preview"]),
issuedAt: 1,
expiresAt: Number.MAX_SAFE_INTEGER,
};

function makeHarness() {
let sequence = 1;
let threads: OrchestrationThreadShell[] = [currentShell];
const details = new Map<string, OrchestrationThread>([[currentThreadId, currentDetail]]);
const commands: OrchestrationCommand[] = [];

const snapshot = (): OrchestrationShellSnapshot => ({
snapshotSequence: sequence,
projects: [project],
threads,
updatedAt: now,
});

const engine = {
readEvents: () => Stream.empty,
streamDomainEvents: Stream.empty,
dispatch: (command: OrchestrationCommand) =>
Effect.sync(() => {
commands.push(command);
sequence += 1;
if (command.type === "thread.create") {
const shell = {
id: command.threadId,
projectId: command.projectId,
title: command.title,
modelSelection: command.modelSelection,
runtimeMode: command.runtimeMode,
interactionMode: command.interactionMode,
branch: command.branch,
worktreePath: command.worktreePath,
latestTurn: null,
createdAt: command.createdAt,
updatedAt: command.createdAt,
archivedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
} satisfies OrchestrationThreadShell;
threads = [...threads, shell];
details.set(command.threadId, {
id: command.threadId,
projectId: command.projectId,
title: command.title,
modelSelection: command.modelSelection,
runtimeMode: command.runtimeMode,
interactionMode: command.interactionMode,
branch: command.branch,
worktreePath: command.worktreePath,
latestTurn: null,
createdAt: command.createdAt,
updatedAt: command.createdAt,
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
});
}
if (command.type === "thread.turn.start") {
threads = threads.map((thread) =>
thread.id === command.threadId
? {
...thread,
latestTurn: {
turnId: TurnId.make("turn-starting"),
state: "running",
requestedAt: command.createdAt,
startedAt: null,
completedAt: null,
assistantMessageId: null,
},
latestUserMessageAt: command.createdAt,
updatedAt: command.createdAt,
}
: thread,
);
}
if (command.type === "thread.meta.update" && command.title !== undefined) {
threads = threads.map((thread) =>
thread.id === command.threadId ? { ...thread, title: command.title! } : thread,
);
}
return { sequence };
}),
} satisfies OrchestrationEngineShape;

const query = {
getShellSnapshot: () => Effect.succeed(snapshot()),
getArchivedShellSnapshot: () =>
Effect.succeed({ ...snapshot(), threads: threads.filter((thread) => thread.archivedAt) }),
getThreadDetailById: (threadId: ThreadId) =>
Effect.succeed(Option.fromNullishOr(details.get(threadId))),
} as unknown as ProjectionSnapshotQueryShape;

const provide = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.provide(layer),
Effect.provideService(OrchestrationEngineService, engine),
Effect.provideService(ProjectionSnapshotQuery, query),
Effect.provide(NodeServices.layer),
);

return { commands, provide };
}

it("derives compact visible titles from prompts", () => {
expect(deriveSpawnedChatTitle(" Review the authentication flow\nIgnore this line")).toBe(
"Review the authentication flow",
);
expect(deriveSpawnedChatTitle("x".repeat(100))).toBe(`${"x".repeat(69)}...`);
});

it.effect("spawns a visible chat that inherits the caller settings and receives its prompt", () => {
const harness = makeHarness();
return harness.provide(
Effect.gen(function* () {
const manager = yield* ChatManager;
const result = yield* manager.spawn(invocation, {
prompt: "Review the authentication flow",
});

expect(result.promptAccepted).toBe(true);
expect(result.chat).toMatchObject({
title: "Review the authentication flow",
projectId,
state: "running",
modelSelection,
runtimeMode: "full-access",
});
expect(result.chat.threadId).not.toBe(currentThreadId);
expect(harness.commands.map((command) => command.type)).toEqual([
"thread.create",
"thread.turn.start",
]);
expect(harness.commands[0]).toMatchObject({
branch: currentShell.branch,
worktreePath: currentShell.worktreePath,
});
expect(harness.commands[1]).toMatchObject({
message: { text: "Review the authentication flow", role: "user", attachments: [] },
});
}),
);
});

it.effect("prevents self-send and self-wait deadlocks", () => {
const harness = makeHarness();
return harness.provide(
Effect.gen(function* () {
const manager = yield* ChatManager;
const sendError = yield* manager
.send(invocation, { threadId: currentThreadId, prompt: "Loop" })
.pipe(Effect.flip);
expect(sendError.code).toBe("invalid_target");

const waitError = yield* manager
.wait(invocation, { threadIds: [currentThreadId], timeoutSeconds: 1 })
.pipe(Effect.flip);
expect(waitError.code).toBe("invalid_target");
expect(harness.commands).toEqual([]);
}),
);
});
Loading
Loading