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
20 changes: 20 additions & 0 deletions apps/server/src/mcp/McpHttpServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,26 @@ it.effect("rejects a string workflow stage by naming the stage shape before the
}).pipe(Effect.provide(layerRecordingTools(calls)));
});

it.effect(
"passes unknown workflow keys to the service, which rejects them, never strips them",
() => {
const calls: Array<unknown> = [];
return Effect.gen(function* () {
const agents = [{ id: "a", task: "Draft." }];
const input = {
name: "review",
stages: [
{ id: "draft", agents, dependsOn: [] },
{ id: "loop", repeat: { stages: [{ id: "fix", agents }], judge: "a", max: 2 } },
],
timeout: 60_000,
};
yield* callTool("t3_workflow_run", input).pipe(Effect.ignore);
expect(calls).toEqual([input]);
}).pipe(Effect.provide(layerRecordingTools(calls)));
},
);

it("advertises workflow stages as objects that need an id", () => {
const schema = advertisedJsonSchema(OrchestratorToolkit.tools.t3_workflow_run) as {
properties: { stages: { items?: { type?: string; required?: Array<string> } } };
Expand Down
4 changes: 3 additions & 1 deletion apps/server/src/mcp/WorkflowRuns.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1269,7 +1269,9 @@ it.layer(layerTest)("t3_workflow_run", (it) => {
const judged = { ok: false, addAgents: [{ template: "rewiter", task: "Fix line 1." }] };
yield* settleChild(critic, `\`\`\`json\n${JSON.stringify(judged)}\n\`\`\``);

const error = 'round 1 critic: addAgents[0]: unknown template "rewiter"';
// The critic was delegated with its templates in its resultSchema, so its reply fails there.
const error =
'round 1 critic: invalid_output: $.addAgents[0].template: not one of ["rewriter"]';
const row = yield* ended(parent.threadId, subagentId);
assert.equal(row?.status, "failed");
assert.equal(JSON.parse(row?.result ?? "{}").error, error);
Expand Down
14 changes: 14 additions & 0 deletions apps/server/src/mcp/advertisedJsonSchema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,17 @@ it("drops JSON noise, merges tagged unions, and keeps null where it is required"
required: ["beforeRunId", "every"],
});
});

it("advertises a struct that keeps unknown keys as the plain struct", () => {
const tool = Tool.make("example", {
parameters: Schema.StructWithRest(Schema.Struct({ id: Schema.String }), [
Schema.Record(Schema.String, Schema.Unknown),
]),
});

expect(advertisedJsonSchema(tool)).toEqual({
type: "object",
properties: { id: { type: "string" } },
required: ["id"],
});
});
15 changes: 14 additions & 1 deletion apps/server/src/mcp/advertisedJsonSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,15 @@ const mergeTaggedObjects = (branches: ReadonlyArray<Json>): JsonObject | undefin
return { type: "object", properties, required: [tag, ...requiredByAll] };
};

const isEmptyObject = (value: Json) => Predicate.isObject(value) && Object.keys(value).length === 0;

const compact = (schema: Json, optional: boolean): Json => {
if (Array.isArray(schema)) return schema.map((item) => compact(item, false));
if (!Predicate.isObject(schema)) return schema;
const required = new Set(Array.isArray(schema.required) ? schema.required : []);
let result: JsonObject = {};
for (const [key, value] of Object.entries(schema)) {
if (key === "additionalProperties" && value === true) continue;
if (key === "additionalProperties" && (value === true || isEmptyObject(value))) continue;
if (SAFE_INTEGER_BOUNDS[key] === value) continue;
result[key] =
key === "properties" && Predicate.isObject(value)
Expand All @@ -85,6 +87,17 @@ const compact = (schema: Json, optional: boolean): Json => {
)
: compact(value, false);
}
// A `Schema.StructWithRest` rest compacts to an `allOf` branch that only restates the type.
if (Array.isArray(result.allOf)) {
const type = result.type;
const branches = result.allOf.filter(
(branch) =>
!Predicate.isObject(branch) ||
!Object.entries(branch).every(([key, value]) => key === "type" && value === type),
);
const { allOf: _allOf, ...rest } = result;
result = branches.length === 0 ? rest : { ...rest, allOf: branches };
}
if (Array.isArray(result.anyOf)) {
const branches = result.anyOf
.flatMap((branch) => (isBareAnyOf(branch) ? branch.anyOf : [branch]))
Expand Down
45 changes: 32 additions & 13 deletions apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,21 +127,40 @@ const TaskCancelTool = Tool.make("task_cancel", {

const workflowDependencies = [...dependencies, WorkflowRuns.WorkflowRuns];

// Stages advertise only their outline to keep the tool list small; the service decodes the full spec.
const WorkflowStage = Schema.Struct({
id: Schema.String,
agents: Schema.optional(Schema.Array(Schema.Unknown)),
repeat: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
}).annotate({ message: "stages[] entries are objects: {id, agents:[…]} or {id, repeat:{…}}" });
// The description types the spec; the schema is an outline the service decodes in full. Unknown keys
// pass through so the service rejects them: stripping them would run a spec the model did not write.
const withRest = <S extends Schema.Struct<Schema.Struct.Fields>>(struct: S) =>
Schema.StructWithRest(struct, [Schema.Record(Schema.String, Schema.Unknown)]);
// Codex sends the items of an array with no item type as JSON strings, so agents are typed objects.
const agents = Schema.optional(Schema.Array(Schema.Record(Schema.String, Schema.Unknown)));
const WorkflowStage = withRest(
Schema.Struct({
id: Schema.String,
agents,
repeat: Schema.optional(
withRest(
Schema.Struct({
stages: Schema.optional(Schema.Array(withRest(Schema.Struct({ agents })))),
}),
),
),
}),
).annotate({ message: "stages[] entries are objects: {id, agents:[…]} or {id, repeat:{…}}" });

const WorkflowRunTool = Tool.make("t3_workflow_run", {
description:
"Run stages in order; returns now, wakes you when done. Stage: `{id,agents:[{id,task,target?,role?,isolation?,resultSchema?}]}` (parallel) or `{id,repeat:{stages,judge,until:{path,equals},max,onExhausted?,dry?,templates?:{name:{task}}}}`. Its judge may return `addAgents:[{template,task?,input?,key?,stage?}]`, `rerun:[stage]`; `dry:N` ends after N rounds of neither. {{stage}},{{stage.agent}},{{feedback}},{{input.x}} insert output.",
parameters: Schema.Struct({
name: TrimmedNonEmptyString,
stages: Schema.Array(WorkflowStage),
timeoutMs: Schema.optional(Schema.Int),
}),
description: `Run agents in stages; returns now, wakes you when done.
type Spec={name:string;stages:Stage[]}
type Stage={id:string;agents:Agent[]}|{id:string;repeat:Loop} // never both; agents parallel
type Agent={id:string;task:string;target?:{model?:string;options?:object}/*omit to inherit model/options; options must match model*/;isolation?:'shared'|'worktree';resultSchema?:JSONSchema}
type Loop={stages:{id:string;agents:Agent[]/*may be empty*/}[];judge?:string/*agent id in LAST stage; defaults to its sole agent*/;until:{path:string/*judge result field, e.g. 'ok'*/;equals:string|number|boolean|null};max:number/*1-10 rounds*/;onExhausted?:'fail'|'pass';dry?:number;templates?:{[name:string]:{task:string}}}
Tasks: {{stageId}} or {{stageId.agentId}} insert earlier results. After a loop use inner stage ids, never its id. Loops rerun stages in order; forward/self references and {{feedback}} read last round (null in round 1). The judge's result must have until's field; its schema is generated if omitted. With templates, judge may return addAgents:{template:string;task?:string;input?:object/*{{input.x}}*/;stage?:string}[] for next round and rerun:stageId[]. dry:N ends after N rounds with neither. Only loop judges add agents; put round 1 inside the loop.`,
parameters: withRest(
Schema.Struct({
name: TrimmedNonEmptyString,
stages: Schema.Array(WorkflowStage),
timeoutMs: Schema.optional(Schema.Int),
}),
),
success: Schema.Struct({
subagentId: NodeId,
next: Schema.Literal(ORCHESTRATOR_MCP_RUNNING_TASK_NEXT),
Expand Down
Loading
Loading