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
34 changes: 33 additions & 1 deletion apps/server/src/mcp/BridgeStatusService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,42 @@ import { EnvironmentId, OrchestratorMcpFailure } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as PeerForwarding from "../peer/PeerForwarding.ts";
import * as Bridge from "./BridgeStatusService.ts";
import * as Invocation from "./McpInvocationContext.ts";
import * as Events from "./McpEvents.ts";
import * as Metrics from "./McpBridgeMetrics.ts";
import * as AutoReview from "../orchestration-v2/ApprovalAutoReviewStatus.ts";
import * as ApprovalWorker from "../orchestration-v2/ApprovalAutoReview.ts";
import * as EventSink from "../orchestration-v2/EventSink.ts";
import * as Sqlite from "../persistence/Sqlite.ts";
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
import * as ProviderInstances from "../provider/ProviderInstanceRegistry.ts";
import * as TextGenerators from "../textGeneration/TextGenerators.ts";
import * as Settings from "../serverSettings.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";

it.effect(
"reports fresh peer probe results and preserves bridge status when links are unavailable",
() =>
Effect.gen(function* () {
const unavailable = yield* Ref.make(false);
const worker = ApprovalWorker.layer.pipe(
Layer.provide(
Layer.mergeAll(
Sqlite.layerMemory,
Settings.layerTest(),
Layer.mock(ThreadManagement.ThreadManagementService)({}),
Layer.mock(ProviderInstances.ProviderInstanceRegistry)({}),
Layer.mock(TextGenerators.TextGenerators)({}),
Layer.mock(EventSink.EventSinkV2)({
latestSequence: () => Effect.succeed(0),
stream: () => Stream.never,
}),
),
),
);
const scope: Invocation.McpInvocationScope = {
environmentId: EnvironmentId.make("here"),
requestNamespace: "outside",
Expand Down Expand Up @@ -82,6 +106,7 @@ it.effect(
yield* Effect.gen(function* () {
const service = yield* Bridge.BridgeStatusService;
const status = yield* service.status();
expect(status.autoReview).toEqual({ status: "healthy", failures: 0, lastError: null });
expect(status.missedScheduledRuns).toEqual([
{
scheduledTaskId: "scheduled-task:late",
Expand All @@ -98,12 +123,19 @@ it.effect(
],
});
yield* Ref.set(unavailable, true);
const autoReview = yield* AutoReview.ApprovalAutoReviewStatus;
yield* autoReview.failed("Subscription overflow; resubscribing");
const workerStatus = yield* autoReview.read;
expect(yield* service.status()).toMatchObject({
linkedEnvironments: null,
daysUntilSessionExpires: 1,
autoReview: workerStatus,
});
expect(workerStatus.status).toBe("degraded");
expect(workerStatus.failures).toBe(1);
expect(workerStatus.lastError).toContain("Subscription overflow");
}).pipe(
Effect.provide(Bridge.layer.pipe(Layer.provide(dependencies))),
Effect.provide(Bridge.layer.pipe(Layer.provide(dependencies), Layer.provideMerge(worker))),
Effect.provideService(Invocation.McpInvocationContext, scope),
);
}),
Expand Down
4 changes: 4 additions & 0 deletions apps/server/src/mcp/BridgeStatusService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ import * as PeerForwarding from "../peer/PeerForwarding.ts";
import * as Invocation from "./McpInvocationContext.ts";
import * as McpEvents from "./McpEvents.ts";
import * as Metrics from "./McpBridgeMetrics.ts";
import * as AutoReview from "../orchestration-v2/ApprovalAutoReviewStatus.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
export const BridgeStatusResult = Schema.Struct({
autoReview: AutoReview.Snapshot,
serviceStartedAt: Schema.String,
tunnel: Schema.NullOr(EnvironmentConnectReachability),
daysUntilSessionExpires: Schema.Number,
Expand Down Expand Up @@ -75,6 +77,7 @@ export const layer = Layer.effect(
const events = yield* McpEvents.McpEvents;
const metrics = yield* Metrics.McpBridgeMetrics;
const forwarding = yield* PeerForwarding.PeerForwarding;
const autoReview = yield* AutoReview.ApprovalAutoReviewStatus;
const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
return BridgeStatusService.of({
status: Effect.fn("BridgeStatusService.status")(function* () {
Expand Down Expand Up @@ -123,6 +126,7 @@ export const layer = Layer.effect(
);
return {
...status,
autoReview: yield* autoReview.read,
linkedEnvironments,
missedScheduledRuns,
toolCalls: yield* metrics.read(scope.client!.sessionId),
Expand Down
20 changes: 19 additions & 1 deletion apps/server/src/mcp/McpApprovalAnswerContext.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import type { EnvironmentId } from "@t3tools/contracts";
import {
type EnvironmentId,
ModelSelection,
OrchestrationV2McpApprovalAnswer,
RuntimeRequestId,
ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Schema from "effect/Schema";

export const ApprovalReviewEscalation = Schema.Struct({
threadId: ThreadId,
requestId: RuntimeRequestId,
decision: Schema.Literal("escalate"),
requestKind: Schema.optional(Schema.String),
prompt: Schema.optional(Schema.String),
answeredAt: OrchestrationV2McpApprovalAnswer.fields.answeredAt,
reviewer: Schema.Struct({ modelSelection: ModelSelection, reason: Schema.String }),
});

export class McpApprovalAnswerContext extends Context.Service<
McpApprovalAnswerContext,
Expand All @@ -8,5 +25,6 @@ export class McpApprovalAnswerContext extends Context.Service<
readonly clientLabel: string;
readonly originEnvironmentId?: EnvironmentId;
readonly note?: string;
readonly reviewer?: { readonly modelSelection: ModelSelection; readonly reason: string };
}
>()("t3/mcp/McpApprovalAnswerContext") {}
8 changes: 6 additions & 2 deletions apps/server/src/mcp/PendingApprovalMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import * as Schema from "effect/Schema";
import * as SqlClient from "effect/sql/SqlClient";

import * as Invocation from "./McpInvocationContext.ts";
import { McpApprovalAnswerContext } from "./McpApprovalAnswerContext.ts";
import { ApprovalReviewEscalation, McpApprovalAnswerContext } from "./McpApprovalAnswerContext.ts";
import {
assertFullAccess,
dispatchFailure,
Expand All @@ -34,7 +34,11 @@ const ApprovalRefusal = Schema.Struct({
attemptedDecision: OrchestrationV2McpApprovalAnswer.fields.decision,
reason: Schema.String,
});
const ApprovalRecord = Schema.Union([OrchestrationV2McpApprovalAnswer, ApprovalRefusal]);
const ApprovalRecord = Schema.Union([
OrchestrationV2McpApprovalAnswer,
ApprovalRefusal,
ApprovalReviewEscalation,
]);
export const ApprovalLogResult = Schema.Struct({
records: Schema.Array(ApprovalRecord),
nextCursor: Schema.NullOr(Schema.Number),
Expand Down
93 changes: 90 additions & 3 deletions apps/server/src/mcp/toolkits/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ import * as McpInvocationContext from "../McpInvocationContext.ts";
import * as McpToolAccessTestkit from "../McpToolAccess.testkit.ts";
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
import { dispatchFailure } from "../threadAccess.ts";
import { McpApprovalAnswerContext } from "../McpApprovalAnswerContext.ts";
import { ApprovalReviewEscalation, McpApprovalAnswerContext } from "../McpApprovalAnswerContext.ts";
import * as EnvironmentHandlers from "./environment/handlers.ts";
import * as AttachmentHandlers from "./attachment/handlers.ts";
import { ThreadToolkit } from "./thread/tools.ts";
Expand Down Expand Up @@ -104,12 +104,14 @@ const decodeMcpAttachmentInput = Schema.decodeUnknownEffect(McpAttachmentInput);
const encodeApprovalAnswer = Schema.encodeSync(
Schema.fromJsonString(OrchestrationV2McpApprovalAnswer),
);
const encodeEscalation = Schema.encodeEffect(Schema.fromJsonString(ApprovalReviewEscalation));
const decodeThreadReadResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadReadResult);
const decodeThreadSearchResult = Schema.decodeUnknownEffect(
ThreadToolkit.tools.t3_thread_search.successSchema,
);

const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe(
Layer.provide(ServerSettings.layerTest()),
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
Layer.provide(Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({})),
Expand Down Expand Up @@ -421,10 +423,24 @@ it.effect("only outside full-access sign-ins answer approvals, with attribution"
answeredAt: "2026-11-12T00:00:00.000Z",
note: "Chris said yes.",
};
const reviewer = {
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "reviewer" },
reason: "Requested work",
};
yield* sql`INSERT INTO mcp_approval_answers (thread_id, request_id, answer_json)
VALUES (${shell.id}, ${requestId}, ${encodeApprovalAnswer(record)})`;
VALUES (${shell.id}, ${requestId}, ${encodeApprovalAnswer({ ...record, reviewer })})`;
const escalation = {
threadId: shell.id,
requestId,
answeredAt: record.answeredAt,
decision: "escalate" as const,
reviewer: { ...reviewer, reason: "Possible spending" },
};
const escalationJson = yield* encodeEscalation(escalation);
yield* sql`INSERT INTO mcp_approval_answers (thread_id, request_id, outcome, answer_json)
VALUES (${shell.id}, ${requestId}, 'refused', ${escalationJson})`;
expect((yield* log(outside("full-access"))).structuredContent).toEqual({
records: [...refused.records, record],
records: [...refused.records, { ...record, reviewer }, escalation],
nextCursor: null,
});
}).pipe(
Expand Down Expand Up @@ -958,6 +974,7 @@ it.effect("requires a projectId to file a scratch thread and returns the moved s
}).pipe(
Effect.provide(
McpHttpServer.layerThreadToolkit.pipe(
Layer.provide(ServerSettings.layerTest()),
Layer.provide(Sqlite.layerMemory),
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
Expand Down Expand Up @@ -1333,6 +1350,7 @@ it.effect("search names the calling thread, so an agent can tell its own match a
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
Layer.provide(Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({})),
Layer.provide(ServerSettings.layerTest()),
Layer.provide(Sqlite.layerMemory),
Layer.provide(NodeServices.layer),
),
Expand Down Expand Up @@ -1362,6 +1380,70 @@ it.effect("a read-only client reads threads and is refused every write before it
runtimeMode: "auto",
acknowledgeOnly: false,
});
expect(configuration.structuredContent).toMatchObject({
autoReview: { override: "inherit", effective: null },
});
for (const access of ["read-only", "approval-required", "auto"] as const) {
const denied = yield* server
.callTool({
name: "t3_thread_configure",
arguments: {
threadId: "other-project-thread",
autoReview: { instanceId: "codex", model: "reviewer" },
},
})
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, clientScope(access)),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(declaredFailure(denied)).toMatchObject({ code: "capability_denied" });
}
for (const override of [{ instanceId: "codex", model: "reviewer" }, null, "inherit"] as const) {
const changed = yield* server
.callTool({
name: "t3_thread_configure",
arguments: {
threadId: "other-project-thread",
autoReview: override,
},
})
.pipe(
Effect.provideService(
McpInvocationContext.McpInvocationContext,
clientScope("full-access"),
),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(changed.isError).toBe(false);
expect(changed.structuredContent).toMatchObject({
autoReview: {
override,
effective: override === "inherit" ? null : override,
},
});
}

for (const change of [
{ modelSelection: { instanceId: "codex", model: "reviewer" } },
{ runtimeMode: "approval-required" },
{ applyAt: "next_turn" },
{ acknowledgeOnly: true },
{ standingRole: "Do not replace the role." },
]) {
const mixed = yield* server
.callTool({
name: "t3_thread_configure",
arguments: { threadId: "other-project-thread", autoReview: null, ...change },
})
.pipe(
Effect.provideService(
McpInvocationContext.McpInvocationContext,
clientScope("full-access"),
),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(declaredFailure(mixed)).toMatchObject({ code: "invalid_request" });
}

const pinned = yield* call("t3_thread_organize", {
action: "pin",
Expand Down Expand Up @@ -1422,6 +1504,7 @@ it.effect("a read-only client reads threads and is refused every write before it
}
expect((yield* acknowledgeAs("full-access", true)).structuredContent).toMatchObject({
acknowledgeOnly: true,
autoReview: { override: "inherit", effective: null },
});
expect(
(yield* call("t3_thread_configure", { threadId: "other-project-thread" })).structuredContent,
Expand Down Expand Up @@ -1457,6 +1540,9 @@ it.effect("a read-only client reads threads and is refused every write before it
standingRoleSetBy: expect.stringMatching(/^session- \(Claude Code\), \d{4}-/),
};
expect(roleSet.structuredContent).toMatchObject(recorded);
expect(roleSet.structuredContent).toMatchObject({
autoReview: { override: "inherit", effective: null },
});
expect(
(yield* call("t3_thread_configure", { threadId: "other-project-thread" })).structuredContent,
).toMatchObject(recorded);
Expand Down Expand Up @@ -1756,6 +1842,7 @@ it.effect.each([
}).pipe(
Effect.provide(
McpHttpServer.layerThreadToolkit.pipe(
Layer.provide(ServerSettings.layerTest()),
Layer.provide(Sqlite.layerMemory),
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provide(NodeCrypto.layer),
Expand Down
32 changes: 31 additions & 1 deletion apps/server/src/mcp/toolkits/thread/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ import { advertisedModel, requireAdvertisedModel } from "../../providerModels.ts
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
import * as PendingApproval from "../../PendingApprovalMcpService.ts";
import * as AutoReviewConfig from "../../../orchestration-v2/ApprovalAutoReviewConfig.ts";
import {
dispatchFailure,
assertFullAccess,
newCommandId,
readCaller,
readThread,
Expand Down Expand Up @@ -169,6 +171,7 @@ const configureAcknowledgeOnly = Effect.fn("mcp.configureAcknowledgeOnly")(funct
modelSelection: thread.modelSelection,
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
autoReview: yield* AutoReviewConfig.read(thread.id).pipe(Effect.mapError(unavailable)),
acknowledgeOnly,
};
});
Expand Down Expand Up @@ -293,6 +296,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
(input) =>
input.modelSelection === undefined &&
input.runtimeMode === undefined &&
input.autoReview === undefined &&
input.applyAt === undefined &&
input.acknowledgeOnly === undefined &&
input.standingRole === undefined,
Expand All @@ -303,6 +307,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
projection: { thread },
} = yield* readThread(input.threadId);
return {
autoReview: yield* AutoReviewConfig.read(thread.id).pipe(Effect.mapError(unavailable)),
...configuration(thread, yield* (yield* ThreadRoles.ThreadRoles).get(thread.id)),
acknowledgeOnly: yield* threads
.acknowledgeOnly(thread.id)
Expand All @@ -316,6 +321,28 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
threads,
projection: { thread },
} = yield* readThread(input.threadId);
if (input.autoReview !== undefined) {
yield* assertFullAccess(yield* readCaller(), "configure approval auto-review");
if (
input.modelSelection !== undefined ||
input.runtimeMode !== undefined ||
input.applyAt !== undefined ||
input.acknowledgeOnly !== undefined ||
input.standingRole !== undefined
) {
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
message: "Set autoReview separately from other thread configuration.",
});
}
const autoReview = yield* AutoReviewConfig.write(thread.id, input.autoReview).pipe(
Effect.mapError(unavailable),
);
return {
...configuration(thread, yield* (yield* ThreadRoles.ThreadRoles).get(thread.id)),
autoReview,
};
}
if (input.acknowledgeOnly !== undefined) {
return yield* configureAcknowledgeOnly(threads, thread, input);
}
Expand Down Expand Up @@ -355,7 +382,10 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
})
.pipe(withMcpCommandActor, Effect.mapError(dispatchFailure));
yield* roles.set(thread.id, input.standingRole, McpInvocationContext.actorLabel(scope));
return configuration(thread, yield* roles.get(thread.id));
return {
...configuration(thread, yield* roles.get(thread.id)),
autoReview: yield* AutoReviewConfig.read(thread.id).pipe(Effect.mapError(unavailable)),
};
}
if (input.runtimeMode !== undefined) {
if (input.modelSelection !== undefined) {
Expand Down
Loading
Loading