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
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@photon-ai/mcp-core",
"version": "0.2.0",
"version": "0.2.1",
"description": "Compile an OpenAPI document into MCP tools and execute them over HTTP.",
"keywords": [
"mcp",
Expand Down
15 changes: 15 additions & 0 deletions packages/core/src/compiler/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,19 @@ export function operationTitle(
return summary || fallback;
}

function operationTags(
operation: Readonly<JsonObject>
): readonly string[] | undefined {
if (!Array.isArray(operation.tags)) {
return;
}
const tags = operation.tags
.filter((tag): tag is string => typeof tag === "string")
.map((tag) => tag.trim())
.filter((tag) => tag.length > 0);
return tags.length > 0 ? tags : undefined;
}

export function compileCapability(
pathOperation: PathOperation,
components: unknown,
Expand All @@ -695,6 +708,7 @@ export function compileCapability(
components,
pinnedHeaders
);
const tags = operationTags(operation);
return {
annotations: {
destructiveHint: extension?.destructive ?? method === "DELETE",
Expand Down Expand Up @@ -722,6 +736,7 @@ export function compileCapability(
...(body === undefined ? {} : { requestMediaType: body.mediaType }),
requiredPermissions: operationPermissions(operation),
successRepresentations: success.representations,
...(tags === undefined ? {} : { tags }),
};
}

Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/release.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export interface Capability {
readonly requestMediaType?: string;
readonly requiredPermissions: readonly string[];
readonly successRepresentations: readonly SuccessRepresentation[];
readonly tags?: readonly string[];
}

export interface ReleaseDocuments {
Expand Down Expand Up @@ -95,6 +96,7 @@ const capabilitySchema = z
requestMediaType: z.string().optional(),
requiredPermissions: z.array(z.string()),
successRepresentations: z.array(successRepresentationSchema).min(1),
tags: z.array(z.string().min(1)).min(1).optional(),
})
.strict()
.superRefine((capability, context) => {
Expand Down Expand Up @@ -494,6 +496,7 @@ function normalizeCapability(
operationPollLimit,
requestMediaType,
successRepresentations,
tags,
...requiredFields
} = capability;

Expand All @@ -519,5 +522,6 @@ function normalizeCapability(
requestMediaType:
normalizeJsonMediaType(requestMediaType) ?? requestMediaType,
}),
...(tags === undefined ? {} : { tags }),
};
}
59 changes: 50 additions & 9 deletions packages/core/src/runtime/execution/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import type {
import { type InvocationDependencies, InvocationError } from "../invoke.js";
import type { ExecutionPrincipal } from "../principal.js";
import type { ActivatedRuntimeRelease } from "../runtime-release.js";
import type { Telemetry } from "../telemetry.js";
import type {
RuntimeToolEvent,
Telemetry,
ToolObserver,
ToolResult,
} from "../telemetry.js";
import {
errorResult,
type Result,
Expand All @@ -20,6 +25,7 @@ import {

export interface RuntimeDependencies extends InvocationDependencies {
readonly event?: Telemetry["event"];
readonly observe?: ToolObserver;
readonly randomBytes: (length: number) => Uint8Array;
readonly record: (
event: Readonly<{ durationMs?: number; name: string; result: string }>
Expand Down Expand Up @@ -161,7 +167,7 @@ async function executeCapabilityInner(
function toolOutcomeName(
outcome: Result,
disposition?: LifecycleDisposition
): string {
): ToolResult {
if (disposition !== undefined) {
return disposition;
}
Expand All @@ -175,6 +181,29 @@ function toolOutcomeName(
return outcome.isError === true ? "error" : "complete";
}

export function toolErrorCode(outcome: Result): string | undefined {
if (outcome.isError !== true) {
return;
}
const { code } = object(outcome.structuredContent);
return typeof code === "string" ? code : undefined;
}

function notify(
observe: ToolObserver | undefined,
event: RuntimeToolEvent
): void {
try {
// An async function is assignable to ToolObserver; swallow its rejection.
const pending: unknown = observe?.(event);
if (pending instanceof Promise) {
pending.catch(() => undefined);
}
} catch {
// Observer failures must never change tool execution or responses.
}
Comment thread
YuniqueUnic marked this conversation as resolved.
Resolved
}

// MCP clients validate any structuredContent against the tool's outputSchema,
// even on an isError result, and reject the whole result when it does not
// match. Every tool result leaves through executeCapability, so no error takes
Expand Down Expand Up @@ -206,11 +235,18 @@ export async function executeCapability(
request.signal.throwIfAborted();
} catch (error) {
if (request.signal.aborted) {
const durationMs = Math.max(0, dependencies.now() - startedAt);
dependencies.record({
durationMs: Math.max(0, dependencies.now() - startedAt),
durationMs,
name: request.execution.capability.operationId,
result: "cancelled",
});
notify(dependencies.observe, {
capability: request.execution.capability,
durationMs,
input: request.input,
kind: "aborted",
});
dependencies.log?.("photon.mcp.tool.event", {
"mcp.result": "cancelled",
"mcp.tool.name": request.execution.capability.operationId,
Expand All @@ -220,16 +256,21 @@ export async function executeCapability(
}
const { outcome } = execution;
const outcomeName = toolOutcomeName(outcome, execution.disposition);
const durationMs = Math.max(0, dependencies.now() - startedAt);
dependencies.record({
durationMs: Math.max(0, dependencies.now() - startedAt),
durationMs,
name: request.execution.capability.operationId,
result: outcomeName,
});
const structured = object(outcome.structuredContent);
const errorType =
outcome.isError === true && typeof structured.code === "string"
? structured.code
: undefined;
const errorType = toolErrorCode(outcome);
notify(dependencies.observe, {
capability: request.execution.capability,
durationMs,
input: request.input,
kind: "completed",
outcome,
result: outcomeName,
});
dependencies.log?.("photon.mcp.tool.event", {
...(errorType === undefined ? {} : { "error.type": errorType }),
"mcp.result": outcomeName,
Expand Down
28 changes: 28 additions & 0 deletions packages/core/src/runtime/telemetry.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,31 @@
import type { Capability } from "../release.js";
import type { Result } from "./execution/response.js";
import type { LifecycleDisposition } from "./execution/state.js";

export type ToolResult =
| "complete"
| "error"
| "pending"
| LifecycleDisposition;

export type RuntimeToolEvent =
| Readonly<{
capability: Capability;
durationMs: number;
input: unknown;
kind: "completed";
outcome: Result;
result: ToolResult;
}>
| Readonly<{
capability: Capability;
durationMs: number;
input: unknown;
kind: "aborted";
}>;

export type ToolObserver = (event: RuntimeToolEvent) => void;

export interface Telemetry {
readonly event: (
name: string,
Expand Down
14 changes: 14 additions & 0 deletions packages/core/test/compiler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1928,6 +1928,20 @@ describe("compileRelease", () => {
);
});

it("preserves ordered nonempty OpenAPI tags as capability metadata", () => {
const result = compileRelease(
makeCompileInput({
operation: { tags: [" Projects ", "", " ", "Read"] },
})
);

expect(capability(result).tags).toEqual(["Projects", "Read"]);
expect(result.tools[0]).not.toHaveProperty("tags");
expect(capability(compileRelease(makeCompileInput()))).not.toHaveProperty(
"tags"
);
});

it("prefers the producer's externalDocs link and omits a link without a tag", () => {
const linked = compileRelease(
makeCompileInput({
Expand Down
77 changes: 77 additions & 0 deletions packages/core/test/execution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import {
type CapabilityExecutionRequest,
executeCapability,
type RuntimeDependencies,
toolErrorCode,
} from "../src/runtime/execution/index.js";
import type { ExecutionPrincipal } from "../src/runtime/principal.js";
import { activateRuntimeRelease } from "../src/runtime/runtime-release.js";
import type { ToolObserver } from "../src/runtime/telemetry.js";
import { makeRuntimeRelease } from "./runtime-release.fixture.js";

const auth: ExecutionPrincipal = {
Expand Down Expand Up @@ -872,6 +874,81 @@ describe("capability execution lifecycle and responses", () => {
});
});

it.each<[string, ToolObserver]>([
[
"throws",
() => {
throw new Error("observer failure");
},
],
["rejects", () => Promise.reject(new Error("observer failure"))],
])("observes the unprojected error without changing the response or record when the observer %s", async (_name, failingObserver) => {
const makeDependencies = (overrides: Partial<RuntimeDependencies>) =>
dependencies(new Response(null, { status: 204 }), undefined, overrides)
.dependency;
const record = vi.fn<RuntimeDependencies["record"]>();
const execution = request("project-1");
const baseline = await executeCapability(
execution,
makeDependencies({ record })
);
const baselineRecords = [...record.mock.calls];
record.mockClear();
const seen = vi.fn<ToolObserver>();
// vi.fn would handle a returned rejection itself, so the failing observer
// is passed through a plain function.
const observe: ToolObserver = (toolEvent) => {
seen(toolEvent);
return failingObserver(toolEvent);
};

const observed = await executeCapability(
execution,
makeDependencies({ observe, record })
);

expect(JSON.stringify(observed)).toBe(JSON.stringify(baseline));
expect(record.mock.calls).toEqual(baselineRecords);
expect(seen).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
capability: projectCapability,
durationMs: 0,
input: execution.input,
kind: "completed",
result: "error",
})
);
const event = seen.mock.calls[0]?.[0];
expect(event?.kind === "completed" && toolErrorCode(event.outcome)).toBe(
"upstream_contract_violation"
);
});

it("observes an in-flight abort once and rethrows the abort reason", async () => {
const controller = new AbortController();
const reason = new Error("caller aborted");
const observe = vi.fn<ToolObserver>();
const { dependency } = dependencies(
undefined,
() => {
controller.abort(reason);
return Promise.reject(reason);
},
{ observe }
);
const execution = request("project-1");

await expect(
executeCapability({ ...execution, signal: controller.signal }, dependency)
).rejects.toBe(reason);
expect(observe).toHaveBeenCalledExactlyOnceWith({
capability: projectCapability,
durationMs: 0,
input: execution.input,
kind: "aborted",
});
});

it("bounds and sensitivity-checks every allowlisted Problem field", async () => {
const { dependency } = dependencies(
new Response(
Expand Down
2 changes: 2 additions & 0 deletions packages/core/test/release.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,8 @@ describe("parseRelease", () => {
successRepresentations: [{ status: 204 }, { status: 204 }],
},
],
["empty tags", { ...capability, tags: [] }],
["an empty tag", { ...capability, tags: [""] }],
[
"wrong representation order",
{
Expand Down
Loading