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
10 changes: 9 additions & 1 deletion apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -823,11 +823,17 @@ const imageToolFailure =
typeof failureText === "string" || failures[0] === undefined
? undefined
: failureText(failures[0].error);
// SCIENT-FORK:START — a declared failure's closed code reaches the agent and analytics.
const code = isOrchestratorMcpFailure(firstFailure) ? firstFailure.code : undefined;
// SCIENT-FORK:END
const result = new McpSchema.CallToolResult({
isError: true,
structuredContent: {
error: {
_tag: errorTag,
// SCIENT-FORK:START — a declared failure's closed code reaches the agent and analytics.
...(code === undefined ? {} : { code }),
// SCIENT-FORK:END
operation,
failureCount: failures.length,
...(message === undefined ? {} : { message }),
Expand All @@ -841,11 +847,13 @@ const imageToolFailure =
},
],
});
// SCIENT-FORK:START — a declared failure's closed code reaches the agent and analytics.
return Effect.logWarning(`${toolName} failed`, {
operation,
errorTag,
failureCount: failures.length,
}).pipe(Effect.as(result));
}).pipe(Effect.andThen(noteToolFailure(firstFailure)), Effect.as(result));
// SCIENT-FORK:END
};

// SCIENT-FORK:START — Request authority and catalogue-checked operations share the MCP boundary.
Expand Down
122 changes: 121 additions & 1 deletion apps/server/src/mcp/McpToolAnalytics.scient.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import {
EnvironmentId,
ProviderInstanceId,
RunId,
ThreadId,
type OrchestrationV2ThreadShell,
} from "@t3tools/contracts";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import { FetchHttpClient } from "effect/http";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";

import * as ServerConfig from "../config.ts";
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
import * as PreviewBrowser from "../preview/PreviewBrowser.ts";
import * as DocumentText from "../provider/DocumentText.ts";
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
import { disabledAnalyticsService } from "../telemetry/ScientAnalytics.ts";
import { BrowserToolCallLedger, BrowserToolCalls } from "../telemetry/ScientMcpAnalytics.ts";
Expand Down Expand Up @@ -183,3 +197,109 @@ it.effect(
);
}),
);

const fullAccessThreadId = ThreadId.make("mcp-scient-full-access-thread");

it.effect("an HTML refusal reports its own code and reason, to the agent and to analytics", () =>
Effect.gen(function* () {
const recorded = yield* Queue.unbounded<Readonly<Record<string, unknown>>>();
const fullAccess = { ...scope, thread: { ...scope.thread!, threadId: fullAccessThreadId } };
const missing = "/scient-missing-dir/figure.html";
const outcome = (
name: string,
args: Record<string, unknown>,
caller: McpInvocationContext.McpInvocationScope = scope,
) =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const result = yield* server
.callTool({
name,
arguments: name === "html_render" ? { ...args, title: "Figure", height: 240 } : args,
})
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, caller),
Effect.provideService(McpSchema.McpServerClient, client),
);
const { errorCode, failureClass, failureOwner } = yield* Queue.take(recorded);
const structured = result.structuredContent as
| { readonly code?: unknown; readonly error?: { readonly code?: unknown } }
| undefined;
return {
agentCode: structured?.error?.code ?? structured?.code,
errorCode,
failureClass,
failureOwner,
};
});
yield* Effect.gen(function* () {
expect(yield* outcome("html_preview", { html: "<p>x</p>", path: missing })).toEqual({
agentCode: "invalid_request",
errorCode: "invalid_request",
failureClass: "html_source_invalid",
failureOwner: "input",
});
expect(yield* outcome("html_preview", { path: missing })).toEqual({
agentCode: "capability_denied",
errorCode: "capability_denied",
failureClass: "html_path_denied",
failureOwner: "environment",
});
expect(yield* outcome("html_preview", { path: missing }, fullAccess)).toEqual({
agentCode: "invalid_request",
errorCode: "invalid_request",
failureClass: "html_render_file",
failureOwner: "input",
});
// html_render returns its declared failure, code included, as the tool's result.
expect(yield* outcome("html_render", { path: missing }, fullAccess)).toMatchObject({
errorCode: "invalid_request",
failureClass: "html_render_file",
failureOwner: "input",
});
}).pipe(
Effect.provide(
McpHttpServer.layerHtmlToolkit.pipe(
Layer.provide(McpToolAccessTestkit.fullAccessCapturedPolicyLayer),
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provide(McpProviderSessions.layer),
Layer.provide(PreviewBrowser.layer),
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "scient-mcp-html-" })),
Layer.provide(
DocumentText.layer.pipe(
Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
),
),
Layer.provide(FetchHttpClient.layer),
Layer.provide(
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: (id) =>
Effect.succeed({
id,
deletedAt: null,
archivedAt: null,
activeRunId: RunId.make("mcp-scient-run"),
providerInstanceId: ProviderInstanceId.make("codex"),
runtimeMode: id === fullAccessThreadId ? "full-access" : "approval-required",
interactionMode: "default",
} as OrchestrationV2ThreadShell),
}),
),
Layer.provide(Layer.succeed(BrowserToolCalls, new BrowserToolCallLedger())),
Layer.provide(
Layer.succeed(
AnalyticsService.AnalyticsService,
AnalyticsService.AnalyticsService.of({
...disabledAnalyticsService,
record: (event, properties) =>
event === "mcp.tool.invoked"
? Queue.offer(recorded, properties ?? {}).pipe(Effect.asVoid)
: Effect.void,
}),
),
),
),
),
);
}),
);
5 changes: 4 additions & 1 deletion apps/server/src/mcp/PreviewAutomationBroker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ import * as AgentInvocationContext from "../scient/operations/AgentInvocationCon
// SCIENT-FORK:END

const HOST_RESPONSE_GRACE_MS = 1_000;
// SCIENT-FORK:START — Scient's account check before an action spends this same budget.
export const PREVIEW_AUTOMATION_DEFAULT_TIMEOUT_MS = 15_000;
// SCIENT-FORK:END

export interface PreviewAutomationInvokeInput {
// SCIENT-FORK:START — Scient callers pass the transport-neutral invocation scope.
Expand Down Expand Up @@ -583,7 +586,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
input.timeoutMs ??
((input.operation === "open" || input.operation === "status") && connection.preferred
? 660_000
: 15_000);
: PREVIEW_AUTOMATION_DEFAULT_TIMEOUT_MS);
// SCIENT-FORK:END
const canReuseAssignedTab =
assigned !== undefined &&
Expand Down
23 changes: 21 additions & 2 deletions apps/server/src/mcp/toolkits/html/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import * as HtmlRender from "../../../htmlRender/HtmlRender.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
import { loadCaller } from "../../threadAccess.ts";
// SCIENT-FORK:START — analytics keeps each refusal's own reason, which the codes below fold.
import { noteToolFailureClass } from "../../../telemetry/ScientMcpAnalytics.ts";
// SCIENT-FORK:END
import { HtmlPreviewToolkit, HtmlRenderToolkit, type HtmlToolkit } from "./tools.ts";

const INVALID_PAGE_ERRORS = new Set([
Expand Down Expand Up @@ -32,13 +35,19 @@ const pageSource = Effect.fn("HtmlToolkit.pageSource")(function* (input: {
return { html: input.html } satisfies HtmlRender.HtmlRenderSource;
}
if (input.path === undefined || input.html !== undefined) {
// SCIENT-FORK:START — analytics keeps each refusal's own reason.
yield* noteToolFailureClass("html_source_invalid");
// SCIENT-FORK:END
return yield* new OrchestratorMcpFailure({
code: "invalid_request",
message: "Pass exactly one of html or path.",
});
}
const { limits } = yield* loadCaller();
if (limits.runtimeMode !== "full-access") {
// SCIENT-FORK:START — analytics keeps each refusal's own reason.
yield* noteToolFailureClass("html_path_denied");
// SCIENT-FORK:END
return yield* new OrchestratorMcpFailure({
code: "capability_denied",
message: "Pass html instead of path: only full-access threads may pass a path.",
Expand All @@ -55,7 +64,12 @@ const handlers = {
const source = yield* pageSource(input);
const { png, ...preview } = yield* htmlRender
.preview({ ...source, width: input.width, appearance: input.appearance })
.pipe(Effect.mapError(toFailure));
// SCIENT-FORK:START — analytics keeps each refusal's own reason.
.pipe(
Effect.tapError((error) => noteToolFailureClass(error._tag)),
Effect.mapError(toFailure),
);
// SCIENT-FORK:END
return {
...preview,
screenshot: {
Expand All @@ -75,7 +89,12 @@ const handlers = {
const source = yield* pageSource(input);
const reference = yield* htmlRender
.publish({ ...source, threadId: thread.threadId, title: input.title, height: input.height })
.pipe(Effect.mapError(toFailure));
// SCIENT-FORK:START — analytics keeps each refusal's own reason.
.pipe(
Effect.tapError((error) => noteToolFailureClass(error._tag)),
Effect.mapError(toFailure),
);
// SCIENT-FORK:END
return {
htmlRender: reference,
message:
Expand Down
6 changes: 4 additions & 2 deletions apps/server/src/mcp/toolkits/html/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@ import * as HtmlRender from "../../../htmlRender/HtmlRender.ts";
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";

// SCIENT-FORK:START — the source rules the handler enforces, stated before a call is refused.
const Html = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512_000)).annotate({
description: "Inline HTML.",
description: "Inline HTML. Pass this or path, not both.",
});

const HtmlPath = Schema.String.annotate({
description: "Absolute .html file path.",
description: "Absolute .html file path. Full-access threads only; others pass html.",
});
// SCIENT-FORK:END

const PAGE_RULES =
"Self-contained: inline <style> and <script>. Local images as absolute paths are inlined. Remote URLs load as-is.";
Expand Down
Loading
Loading