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
4 changes: 4 additions & 0 deletions apps/server/src/auth/EnvironmentAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ export interface AuthenticatedSession {
readonly subject: string;
readonly method: ServerAuthSessionMethod;
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
/** Server-stored client metadata; `deviceType: "bot"` marks a CLI-issued session. */
readonly client?: Pick<AuthClientMetadata, "label" | "deviceType">;
readonly proofKeyThumbprint?: string;
readonly expiresAt?: DateTime.DateTime;
}
Expand Down Expand Up @@ -773,6 +775,7 @@ export const make = Effect.gen(function* () {
subject: session.subject,
method: session.method,
scopes: session.scopes,
client: session.client,
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
Expand Down Expand Up @@ -1327,6 +1330,7 @@ export const make = Effect.gen(function* () {
subject: session.subject,
method: session.method,
scopes: session.scopes,
client: session.client,
...(session.proofKeyThumbprint
? { proofKeyThumbprint: session.proofKeyThumbprint }
: {}),
Expand Down
96 changes: 96 additions & 0 deletions apps/server/src/mcp/toolkits/core.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { RuntimeModeChangeActor } from "../../orchestration-v2/DispatchModeLimit.ts";
import { CommandActor } from "../../orchestration-v2/CommandActor.ts";
import * as McpEvents from "../McpEvents.ts";
import * as McpRequestLog from "../../persistence/McpRequestLog.ts";
import * as BridgeStatusService from "../BridgeStatusService.ts";
Expand Down Expand Up @@ -588,6 +589,101 @@ it.effect("an answered question reports already answered instead of not found",
);
});

it.effect(
"stamps an MCP question answer as an agent's or outside client's, never the owner's",
() => {
const shell = McpToolAccessTestkit.liveThreadShell(threadId);
const requestId = RuntimeRequestId.make("pending-question");
const projection = McpToolAccessTestkit.idleThreadProjection(shell);
const answeredBy: Array<unknown> = [];
const outside: McpInvocationContext.McpInvocationScope = {
...scope,
thread: undefined,
client: {
sessionId: "outside",
label: "Outside client",
access: "full-access",
linked: false,
},
};
return Effect.gen(function* () {
const server = yield* McpServer.McpServer;
for (const invocation of [scope, outside]) {
const result = yield* server
.callTool({
name: "t3_pending_request",
arguments: { action: "respond", threadId, requestId, answers: { size: "large" } },
})
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(result.isError).not.toBe(true);
}
expect(answeredBy).toEqual(["agent", "mcp_client"]);
}).pipe(
Effect.provide(
layerThreadToolkit.pipe(
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provide(NodeCrypto.layer),
Layer.provide(
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: () => Effect.succeed(shell),
getProjectThreadRecords: () =>
Effect.succeed({
...projection,
runtimeRequests: [
{
id: requestId,
nodeId: NodeId.make("root"),
providerTurnId: null,
nativeRequestRef: null,
kind: "user_input",
status: "pending",
responseCapability: { type: "message" },
createdAt: shell.createdAt,
resolvedAt: null,
},
],
turnItems: [
{
id: TurnItemId.make("pending-question-item"),
threadId,
runId: null,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 0,
status: "running",
title: null,
startedAt: shell.createdAt,
completedAt: null,
updatedAt: shell.updatedAt,
type: "user_input_request",
requestId,
questions: [],
},
],
}),
dispatch: () =>
Effect.gen(function* () {
answeredBy.push(
Option.getOrUndefined(
Option.map(yield* Effect.serviceOption(CommandActor), (actor) => actor.kind),
),
);
return { sequence: 1, storedEvents: [] };
}),
}),
),
),
),
);
},
);

it("bounds public command rejections and redacts internal dispatch causes", () => {
const command = { commandId: CommandId.make("mcp-core-command"), commandType: "thread.settle" };
expect(
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/mcp/toolkits/ledger/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ export const LedgerToolkit = Toolkit.make(
Tool.make("ledger_upsert", {
...common,
description:
"Create or partially update work by a stable `key`. New items need title, ownerKind and ownerName. Omitted fields stay; null clears a nullable field. Requires operate access. approvalNote records context and grants no approval.",
"Create or partially update work by a stable `key`. New items need title, ownerKind and ownerName. Omitted fields stay; null clears a nullable field. Requires operate access. approvalNote grants no approval. For Chris's approval, ask him in a dialog whose question has `Ledger key: <key>` on its own line, then pass `approval.source` (itemId, sourceThreadId from t3_thread_read); the server verifies and quotes it, or refuses. `approval: null` revokes.",
parameters: WorkLedgerUpsertInput,
success: WorkLedgerUpsertResult,
}).annotate(Tool.Destructive, true),
Tool.make("ledger_query", {
...common,
description:
"Read compact work ledger rows by status, ownerKind, ownerName, waitReason, due or updatedSince (inclusive). Ordered by key; continue with nextCursor. Default 25 rows.",
"Read compact work ledger rows by status, ownerKind, ownerName, waitReason, due, approved or updatedSince (inclusive). Ordered by key; continue with nextCursor. Default 25 rows.",
parameters: WorkLedgerQueryInput,
success: WorkLedgerQueryResult,
})
Expand Down
13 changes: 11 additions & 2 deletions apps/server/src/mcp/toolkits/thread/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { RuntimeModeChangeActor } from "../../../orchestration-v2/DispatchModeLimit.ts";
import { CommandActor } from "../../../orchestration-v2/CommandActor.ts";
import {
ProviderRequestKind,
type CommandId,
Expand Down Expand Up @@ -47,14 +48,22 @@ function queueEntry(
truncated: characters.length > limit,
};
}
const withMcpCommandActor = Effect.fn("mcp.withCommandActor")(function* <A, E, R>(
effect: Effect.Effect<A, E, R>,
) {
const scope = yield* McpInvocationContext.McpInvocationContext;
return yield* Effect.provideService(effect, CommandActor, {
kind: scope.thread === undefined ? "mcp_client" : "agent",
});
});
const dispatch = Effect.fn("mcp.dispatchThreadCommand")(function* (
threadId: ThreadId | undefined,
command: (common: { commandId: CommandId; threadId: ThreadId }) => OrchestrationV2Command,
) {
const { threads, projection } = yield* readThread(threadId);
const result = yield* threads
.dispatch(command({ commandId: yield* newCommandId(), threadId: projection.thread.id }))
.pipe(Effect.mapError(dispatchFailure));
.pipe(withMcpCommandActor, Effect.mapError(dispatchFailure));
return { sequence: result.sequence };
});

Expand Down Expand Up @@ -342,7 +351,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
requestId,
answers,
})
.pipe(Effect.mapError(dispatchFailure));
.pipe(withMcpCommandActor, Effect.mapError(dispatchFailure));
return { sequence: result.sequence };
}),
),
Expand Down
41 changes: 41 additions & 0 deletions apps/server/src/orchestration-v2/CommandActor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { describe, expect, it } from "@effect/vitest";
import { ownerClientActor } from "./CommandActor.ts";

describe("ownerClientActor", () => {
it.each([
[
"a cloud-connect desktop",
"dpop-access-token",
{ deviceType: "desktop", label: "Chris's Mac" },
"Chris's Mac",
],
["a paired phone", "dpop-access-token", { deviceType: "mobile" }, "dpop-access-token"],
[
"the desktop app",
"bearer-access-token",
{ deviceType: "desktop", label: "Desktop" },
"Desktop",
],
[
"a browser cookie",
"browser-session-cookie",
{ deviceType: "unknown", label: "Firefox" },
"Firefox",
],
] as const)("answers as the owner from %s", (_name, method, client, clientLabel) => {
expect(ownerClientActor({ sessionId: "0123456789abcdef", method, client })).toEqual({
kind: "owner_client",
client: { sessionId: "01234567", clientLabel },
});
});

it("gives a `t3 auth session issue` session no actor, whatever subject it claims", () => {
expect(
ownerClientActor({
sessionId: "0123456789abcdef",
method: "bearer-access-token",
client: { deviceType: "bot", label: "cloud-connect" },
}),
).toBeUndefined();
});
});
35 changes: 35 additions & 0 deletions apps/server/src/orchestration-v2/CommandActor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import type {
ServerAuthSessionMethod,
UserInputAnsweredBy,
UserInputAnsweringClient,
} from "@t3tools/contracts";
import * as Context from "effect/Context";

/**
* Who dispatched a command, provided by the transport that received it and never read from the
* command, so a client cannot claim to be the owner. Absent means unknown and verifies as nobody.
*/
export class CommandActor extends Context.Service<
CommandActor,
{ readonly kind: UserInputAnsweredBy; readonly client?: UserInputAnsweringClient }
>()("t3/orchestration-v2/CommandActor") {}

/**
* The owner actor for a WebSocket session, or none. `t3 auth session issue` sessions are stamped
* `bot` by the server, so a local process cannot answer as the owner with one. A session paired
* from `t3 auth pairing create` looks like any paired device; ADR 0015 records that limit.
*/
export const ownerClientActor = (session: {
readonly sessionId: string;
readonly method: ServerAuthSessionMethod;
readonly client?: { readonly label?: string; readonly deviceType?: string };
}): CommandActor["Service"] | undefined =>
session.client === undefined || session.client.deviceType === "bot"
? undefined
: {
kind: "owner_client",
client: {
sessionId: session.sessionId.slice(0, 8),
clientLabel: session.client.label ?? session.method,
},
};
12 changes: 12 additions & 0 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ import {
} from "./ContextHandoffService.ts";
import { notificationTurnItem } from "@t3tools/provider-core/server/notification";
import { McpApprovalAnswerContext } from "../mcp/McpApprovalAnswerContext.ts";
import { CommandActor } from "./CommandActor.ts";
import { quoteUserInputAnswers } from "./userInputAnswerQuotes.ts";
import {
cancelledBeforeStart,
continuationFailedBeforePrompt,
Expand Down Expand Up @@ -10919,6 +10921,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}

const approvalTurnItem = context.item;
const answerActor = yield* Effect.serviceOption(CommandActor);
const mcpAnswer = yield* Effect.serviceOption(McpApprovalAnswerContext);
if (
Option.isSome(mcpAnswer) &&
Expand Down Expand Up @@ -11190,6 +11193,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {
questionAnswer: {
requestId: command.requestId,
...(Option.isSome(answerActor)
? {
answeredBy: answerActor.value.kind,
...(answerActor.value.client === undefined
? {}
: { answeringClient: answerActor.value.client }),
}
: {}),
quotesById: quoteUserInputAnswers(approvalTurnItem.questions, answers),
answers,
attachmentsByQuestionId: command.attachmentsByQuestionId ?? {},
questionTextById: Object.fromEntries(
Expand Down
18 changes: 17 additions & 1 deletion apps/server/src/orchestration-v2/runtimeLayer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
import * as Orchestrator from "./Orchestrator.ts";
import { CommandActor } from "./CommandActor.ts";
import { ROLLBACK_FAILED_MESSAGE } from "./CheckpointRollbackService.ts";
import * as EffectWorker from "./EffectWorker.ts";
import * as EffectOutbox from "./EffectOutbox.ts";
Expand Down Expand Up @@ -2166,7 +2167,12 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
requestId,
answers: { color: " Blue ", sizes: ["Small", "Large"], note: "" },
};
const accepted = yield* orchestrator.dispatch(command);
const accepted = yield* orchestrator.dispatch(command).pipe(
Effect.provideService(CommandActor, {
kind: "owner_client",
client: { sessionId: "session1", clientLabel: "Chris's Mac" },
}),
);
const repeated = yield* orchestrator.dispatch(command);
assert.equal(repeated.sequence, accepted.sequence);
const answered = yield* orchestrator.getThreadProjection(threadId);
Expand All @@ -2179,6 +2185,16 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
if (answeredItem?.type === "user_input_request") {
assert.deepEqual(answeredItem.questionAnswer, {
requestId,
answeredBy: "owner_client",
answeringClient: { sessionId: "session1", clientLabel: "Chris's Mac" },
quotesById: {
color: [{ kind: "text", text: "Blue", prefilled: false }],
sizes: [
{ kind: "text", text: "Small", prefilled: false },
{ kind: "text", text: "Large", prefilled: false },
],
note: [{ kind: "text", text: "", prefilled: false }],
},
answers: command.answers,
attachmentsByQuestionId: {},
questionTextById: {
Expand Down
Loading
Loading