The open-source agent harness - the runtime layer that turns an LLM into a working agent.
AGE-1578: Return 422 for semantic API errors (#89)
Bhavesh Patel398414929030
diff --git a/fern/openapi/openapi.json b/fern/openapi/openapi.jsonindex 9cc8dccf3..3cb0d8d05 100644--- a/fern/openapi/openapi.json+++ b/fern/openapi/openapi.json@@ -4399,7 +4399,7 @@}}},- "description": "DCR or authorize URL construction failed (e.g. server lacks registration_endpoint)."+ "description": "Invalid redirect_url."},"404": {"content": {@@ -4411,6 +4411,26 @@},"description": "MCP server not found."},+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "DCR could not be completed for this server (e.g. it lacks a registration_endpoint)."+ },+ "424": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "The authorization server failed dynamic client registration or authorization startup."+ },"500": {"content": {"application/json": {@@ -4761,7 +4781,7 @@}}},- "description": "Invalid request body, or named session rejected an agent update."+ "description": "Invalid request body."},"404": {"content": {@@ -4781,7 +4801,7 @@}}},- "description": "The agent spec is valid but references a resource this server does not provide (e.g. model, MCP server, skill, or sandbox)."+ "description": "Named session rejected an agent update, or the agent spec references a resource this server does not provide (e.g. model, MCP server, skill, or sandbox)."}},"summary": "Update a session",@@ -5126,7 +5146,7 @@}}},- "description": "The session is valid but a required resource is no longer available (e.g. named agent, model, MCP server, skill, or sandbox provider)."+ "description": "The request is well-formed but cannot be processed: a referenced resource is missing (named agent, model, MCP server, skill, or sandbox provider), sandbox is required but unavailable (e.g. file uploads), or the turn input conflicts with current state (e.g. unresolved tool calls or approvals, tool name collision)."}},"summary": "Create and execute a turn in a session",@@ -5602,6 +5622,16 @@}},"description": "Invalid request body."+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "The server cannot satisfy `auth.type: dcr` (e.g. it advertises no registration_endpoint)."}},"summary": "Create or replace an MCP server",diff --git a/packages/harness/src/core/errors.ts b/packages/harness/src/core/errors.tsindex 554133bd4..d59c7789d 100644--- a/packages/harness/src/core/errors.ts+++ b/packages/harness/src/core/errors.ts@@ -1,5 +1,5 @@export type AgentHarnessErrorCode =- | 'invalid_agent_input'+ | 'invalid_file_input'| 'invalid_send_input'| 'agent_sandbox_required'| 'tool_name_collision'@@ -17,10 +17,10 @@ export class AgentHarnessError extends Error {}}-export class InvalidAgentInputError extends AgentHarnessError {+export class InvalidFileInputError extends AgentHarnessError {constructor(message: string, options?: ErrorOptions) {- super('invalid_agent_input', message, options);- this.name = 'InvalidAgentInputError';+ super('invalid_file_input', message, options);+ this.name = 'InvalidFileInputError';}}@@ -47,8 +47,8 @@ export class ToolNameCollisionError extends AgentHarnessError {/*** A remote MCP connection or tool call failed. Harness code can't throw the gateway's HTTPException,- * so it throws this instead and carries `statusCode` (401 auth, 403 tool, 400 selector, 502 transport)- * that the gateway boundary turns back into the right HTTP status.+ * so it throws this instead and carries `statusCode` (401 auth, 403 tool, 400 malformed value,+ * 422 well-formed but unprocessable, 502 transport) that the boundary turns back into an HTTP status.*/export class McpConnectionError extends AgentHarnessError {constructor(@@ -66,7 +66,7 @@ export class McpConnectionError extends AgentHarnessError {*/export class McpDcrConfigurationError extends McpConnectionError {constructor(message: string, options?: ErrorOptions) {- super(message, 400, options);+ super(message, 422, options);this.name = 'McpDcrConfigurationError';}}diff --git a/packages/harness/src/core/mcp/ToolSet.ts b/packages/harness/src/core/mcp/ToolSet.tsindex d75244400..1fcc725c2 100644--- a/packages/harness/src/core/mcp/ToolSet.ts+++ b/packages/harness/src/core/mcp/ToolSet.ts@@ -54,7 +54,7 @@ export class ToolSet implements IToolSet {if (missingTools.length > 0) {throw new McpConnectionError(`Requested tools not found in MCP server ${this.name}: ${missingTools.join(', ')}`,- 400,+ 422,);}diff --git a/packages/harness/src/core/runtime/UserInputMessage.ts b/packages/harness/src/core/runtime/UserInputMessage.tsindex f72e61810..64c3a28db 100644--- a/packages/harness/src/core/runtime/UserInputMessage.ts+++ b/packages/harness/src/core/runtime/UserInputMessage.ts@@ -1,5 +1,5 @@import type { ChatCompletionContentPart } from 'openai/resources/chat';-import { AgentSandboxRequiredError, InvalidAgentInputError } from '../errors';+import { AgentSandboxRequiredError, InvalidFileInputError } from '../errors';import {EventType,type AgentInputUserMessage,@@ -42,7 +42,7 @@ function isImageMime(mime: string): boolean {function parseMimeFromFileData(fileData: string): string {const match = /^data:([^;,]+)/.exec(fileData);if (!match?.[1]) {- throw new InvalidAgentInputError('File data URI is missing or has unparseable MIME type');+ throw new InvalidFileInputError('File data URI is missing or has unparseable MIME type');}return match[1];}@@ -50,28 +50,28 @@ function parseMimeFromFileData(fileData: string): string {function extractBase64(dataUri: string): Buffer {const commaIndex = dataUri.indexOf(',');if (commaIndex === -1) {- throw new InvalidAgentInputError('File data URI has no base64 payload');+ throw new InvalidFileInputError('File data URI has no base64 payload');}const raw = dataUri.substring(commaIndex + 1);if (!raw) {- throw new InvalidAgentInputError('File data URI has empty base64 payload');+ throw new InvalidFileInputError('File data URI has empty base64 payload');}const buffer = Buffer.from(raw, 'base64');if (buffer.length === 0) {- throw new InvalidAgentInputError('File data URI decoded to zero bytes');+ throw new InvalidFileInputError('File data URI decoded to zero bytes');}return buffer;}function validatePublicFilename(filename: string): void {if (!filename.length) {- throw new InvalidAgentInputError('File name must not be empty');+ throw new InvalidFileInputError('File name must not be empty');}const normalized = filename.replace(/\\/g, '/');const parts = normalized.split('/');for (const part of parts) {if (part === '..') {- throw new InvalidAgentInputError(`File name contains path traversal: ${filename}`);+ throw new InvalidFileInputError(`File name contains path traversal: ${filename}`);}}}@@ -131,7 +131,7 @@ export async function processAgentUserInput(for (const filePart of fileParts) {const filename = filePart.name.replace(/^\/+/, '');if (!filename.length) {- throw new InvalidAgentInputError('File name must not be empty');+ throw new InvalidFileInputError('File name must not be empty');}validatePublicFilename(filename);diff --git a/packages/harness/tests/core/mcp/remoteMcpServer.test.ts b/packages/harness/tests/core/mcp/remoteMcpServer.test.tsindex c41b81c24..3ecb2af15 100644--- a/packages/harness/tests/core/mcp/remoteMcpServer.test.ts+++ b/packages/harness/tests/core/mcp/remoteMcpServer.test.ts@@ -172,18 +172,18 @@ describe('RemoteMCP + ToolSet', () => {expect(server.getAllowedToolNamesForSandbox()).toEqual(['read_thing']);});- it('throws a 400 McpConnectionError when a literal enable tool is missing', async () => {+ it('throws a 422 McpConnectionError when a literal enable tool is missing', async () => {installFakeConnection();const server = makeServer({selectors: { enableTools: ['does_not_exist'], disableTools: [], preloadTools: [] },});await expect(server.listTools()).rejects.toMatchObject({constructor: McpConnectionError,- statusCode: 400,+ statusCode: 422,});});- it('does not throw the missing-enable-literal 400 during annotation lookups (only explicit listTools)', async () => {+ it('does not throw the missing-enable-literal 422 during annotation lookups (only explicit listTools)', async () => {const state = installFakeConnection();const server = makeServer({selectors: { enableTools: ['does_not_exist'], disableTools: [], preloadTools: [] },@@ -195,7 +195,7 @@ describe('RemoteMCP + ToolSet', () => {});expect(state.connectCalls).toBe(1);// The guard still fires on an explicit listTools().- await expect(server.listTools()).rejects.toMatchObject({ statusCode: 400 });+ await expect(server.listTools()).rejects.toMatchObject({ statusCode: 422 });});it('rejects a disallowed tool call with a 403 McpConnectionError', async () => {diff --git a/packages/harness/tests/core/runtime/userInputMessage.test.ts b/packages/harness/tests/core/runtime/userInputMessage.test.tsindex 8e029579f..c11662be8 100644--- a/packages/harness/tests/core/runtime/userInputMessage.test.ts+++ b/packages/harness/tests/core/runtime/userInputMessage.test.ts@@ -1,4 +1,4 @@-import { AgentSandboxRequiredError, InvalidAgentInputError } from '../../../src/core/errors';+import { AgentSandboxRequiredError, InvalidFileInputError } from '../../../src/core/errors';import { EventType } from '../../../src/core/events/schema';import {isEmptyMessageContent,@@ -52,7 +52,7 @@ describe('UserInputMessage validation', () => {],};- await expect(processAgentUserInput(msg, sandbox)).rejects.toBeInstanceOf(InvalidAgentInputError);+ await expect(processAgentUserInput(msg, sandbox)).rejects.toBeInstanceOf(InvalidFileInputError);await expect(processAgentUserInput(msg, sandbox)).rejects.toMatchObject({message: 'File name must not be empty',});@@ -70,7 +70,7 @@ describe('UserInputMessage validation', () => {],};- await expect(processAgentUserInput(msg, sandbox)).rejects.toBeInstanceOf(InvalidAgentInputError);+ await expect(processAgentUserInput(msg, sandbox)).rejects.toBeInstanceOf(InvalidFileInputError);await expect(processAgentUserInput(msg, sandbox)).rejects.toMatchObject({message: 'File name contains path traversal: ../secrets.txt',});@@ -88,7 +88,7 @@ describe('UserInputMessage validation', () => {],};- await expect(processAgentUserInput(msg, sandbox)).rejects.toBeInstanceOf(InvalidAgentInputError);+ await expect(processAgentUserInput(msg, sandbox)).rejects.toBeInstanceOf(InvalidFileInputError);await expect(processAgentUserInput(msg, sandbox)).rejects.toMatchObject({message: 'File data URI is missing or has unparseable MIME type',});diff --git a/packages/sdk/.fern/metadata.json b/packages/sdk/.fern/metadata.jsonindex 4931b8405..fe0394ea6 100644--- a/packages/sdk/.fern/metadata.json+++ b/packages/sdk/.fern/metadata.json@@ -27,7 +27,7 @@"streamType": "web","useDefaultRequestParameterValues": true},- "originGitCommit": "726b897b61e31bb94007a9f07937edb42ebc0135",+ "originGitCommit": "297c5b1fc240cff72f32bffbc241701aa6a24885","originGitCommitIsDirty": true,"invokedBy": "ci","requestedVersion": "0.0.0",diff --git a/packages/sdk/src/api/resources/mcpServers/client/Client.ts b/packages/sdk/src/api/resources/mcpServers/client/Client.tsindex d4e39b809..fa1bddcee 100644--- a/packages/sdk/src/api/resources/mcpServers/client/Client.ts+++ b/packages/sdk/src/api/resources/mcpServers/client/Client.ts@@ -91,6 +91,8 @@ export class McpServersClient {** @throws {@link TrueForge.BadRequestError}* @throws {@link TrueForge.NotFoundError}+ * @throws {@link TrueForge.UnprocessableEntityError}+ * @throws {@link TrueForge.FailedDependencyError}* @throws {@link TrueForge.InternalServerError}* @throws {@link errors.TrueForgeError}* @throws {@link errors.TrueForgeTimeoutError}@@ -172,6 +174,28 @@ export class McpServersClient {}),_response.rawResponse,);+ case 422:+ throw new TrueForge.UnprocessableEntityError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 424:+ throw new TrueForge.FailedDependencyError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );case 500:throw new TrueForge.InternalServerError(serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {diff --git a/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts b/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.tsindex 5fa830043..4e514a272 100644--- a/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts+++ b/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts@@ -90,6 +90,7 @@ export class McpServersClient {* @param {McpServersClient.RequestOptions} requestOptions - Request-specific configuration.** @throws {@link TrueForge.BadRequestError}+ * @throws {@link TrueForge.UnprocessableEntityError}* @throws {@link errors.TrueForgeError}* @throws {@link errors.TrueForgeTimeoutError}*@@ -166,6 +167,17 @@ export class McpServersClient {}),_response.rawResponse,);+ case 422:+ throw new TrueForge.UnprocessableEntityError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );default:throw new errors.TrueForgeError({statusCode: _response.error.statusCode,diff --git a/packages/sdk/tests/wire/mcpServers.test.ts b/packages/sdk/tests/wire/mcpServers.test.tsindex eb64a4043..84ba2aaea 100644--- a/packages/sdk/tests/wire/mcpServers.test.ts+++ b/packages/sdk/tests/wire/mcpServers.test.ts@@ -95,6 +95,44 @@ describe("McpServersClient", () => {const rawResponseBody = { error: { message: "message" } };+ server+ .mockEndpoint()+ .get("/api/v1/mcp-servers/name/authorize")+ .respondWith()+ .statusCode(422)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.mcpServers.authorize("name");+ }).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);+ });++ test("authorize (5)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });++ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .get("/api/v1/mcp-servers/name/authorize")+ .respondWith()+ .statusCode(424)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.mcpServers.authorize("name");+ }).rejects.toThrow(TrueForgeTypes.FailedDependencyError);+ });++ test("authorize (6)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });++ const rawResponseBody = { error: { message: "message" } };+server.mockEndpoint().get("/api/v1/mcp-servers/name/authorize")diff --git a/packages/sdk/tests/wire/settings/mcpServers.test.ts b/packages/sdk/tests/wire/settings/mcpServers.test.tsindex 85131b5f3..82302936e 100644--- a/packages/sdk/tests/wire/settings/mcpServers.test.ts+++ b/packages/sdk/tests/wire/settings/mcpServers.test.ts@@ -113,6 +113,29 @@ describe("McpServersClient", () => {}).rejects.toThrow(TrueForgeTypes.BadRequestError);});+ test("upsert (3)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });+ const rawRequestBody = { name: "xy", type: "remote", url: "url" };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .put("/api/v1/settings/mcp-servers")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(422)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.settings.mcpServers.upsert({+ name: "xy",+ url: "url",+ });+ }).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);+ });+test("catalog", async () => {const server = mockServerPool.createServer();const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });diff --git a/packages/server/src/apis/mcpServers.ts b/packages/server/src/apis/mcpServers.tsindex f842cbc7e..cc356ba61 100644--- a/packages/server/src/apis/mcpServers.ts+++ b/packages/server/src/apis/mcpServers.ts@@ -146,13 +146,13 @@ export function createSettingsMcpServersRouter(deps: SettingsMcpServersRouterDep});} catch (error) {// Permanent config error (server advertises no DCR support): a retry can never succeed, so- // surface it now as a 400 for immediate feedback instead of a silently-broken server.+ // surface it now as a 422 for immediate feedback instead of a silently-broken server.if (error instanceof McpDcrConfigurationError) {deps.logger.error(`DCR misconfiguration for "${record.manifest.name}"; rejecting upsert`,extractErrorLogFields(error),);- return c.json({ error: { message: error.message } }, 400);+ return c.json({ error: { message: error.message } }, 422);}// Transient (network / timeout / flaky authorization server): keep the saved server and let// the next authorize retry, rather than failing the upsert on a temporary fault.@@ -258,6 +258,12 @@ export function createMcpServersRouter(deps: McpServersRouterDeps) {if (error.statusCode === 400) {return c.json({ error: { message: error.message } }, 400);}+ if (error.statusCode === 422) {+ return c.json({ error: { message: error.message } }, 422);+ }+ if (error.statusCode === 424) {+ return c.json({ error: { message: error.message } }, 424);+ }return c.json({ error: { message: error.message } }, 500);}deps.logger.error(`MCP authorize unexpected failure for "${name}"`, extractErrorLogFields(error));diff --git a/packages/server/src/apis/sessions.ts b/packages/server/src/apis/sessions.tsindex a39a157c1..dbc6ba32c 100644--- a/packages/server/src/apis/sessions.ts+++ b/packages/server/src/apis/sessions.ts@@ -240,7 +240,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {const { session_id: sessionId } = c.req.valid('param');const body = c.req.valid('json');// Draft (value) sessions may replace their inline agent; named (ref) sessions- // cannot — the store rejects that with SessionStoreInvariantError → 400 below.+ // cannot — the store rejects that with SessionStoreInvariantError → 422 below.if (body.agent !== undefined) {await validateAgentSpec({spec: body.agent.agent_spec,@@ -263,7 +263,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);}if (error instanceof SessionStoreInvariantError) {- return c.json({ error: { message: error.message } }, 400);+ return c.json({ error: { message: error.message } }, 422);}throw error;}diff --git a/packages/server/src/apis/turns.ts b/packages/server/src/apis/turns.tsindex 7e2090d97..fee30f200 100644--- a/packages/server/src/apis/turns.ts+++ b/packages/server/src/apis/turns.ts@@ -483,7 +483,17 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {return c.json({ error: { message: error.message } }, 404);}if (error instanceof AgentHarnessError && !(error instanceof McpConnectionError)) {- return c.json({ error: { message: error.message } }, 400);+ switch (error.code) {+ case 'invalid_file_input':+ return c.json({ error: { message: error.message } }, 400);+ case 'invalid_send_input':+ case 'agent_sandbox_required':+ case 'tool_name_collision':+ return c.json({ error: { message: error.message } }, 422);+ case 'capability_state_error':+ case 'mcp_connection_failed':+ throw error;+ }}throw error;}diff --git a/packages/server/src/mcp/auth/mcpDcr.ts b/packages/server/src/mcp/auth/mcpDcr.tsindex 8d3c28379..da169d996 100644--- a/packages/server/src/mcp/auth/mcpDcr.ts+++ b/packages/server/src/mcp/auth/mcpDcr.ts@@ -55,7 +55,7 @@ async function registerMcpClientWithAuthMethodFallback(params: {if (!(firstError instanceof InvalidClientMetadataError)) {throw new McpConnectionError(`Failed to dynamically register OAuth client for MCP server '${mcpServerName}'`,- 400,+ 424,{ cause: firstError instanceof Error ? firstError : undefined },);}@@ -64,7 +64,7 @@ async function registerMcpClientWithAuthMethodFallback(params: {} catch (secondError: unknown) {throw new McpConnectionError(`Failed to dynamically register OAuth client for MCP server '${mcpServerName}'`,- 400,+ 424,{ cause: secondError instanceof Error ? secondError : firstError },);}@@ -72,7 +72,7 @@ async function registerMcpClientWithAuthMethodFallback(params: {if (!fullInfo.client_id) {throw new McpConnectionError(`Authorization server for MCP server '${mcpServerName}' returned a client response without client_id`,- 400,+ 424,);}return {@@ -176,7 +176,7 @@ export async function buildMcpAuthorizationUrl(params: {state,});} catch (error: unknown) {- throw new McpConnectionError(`Failed to start OAuth authorization for MCP server '${params.mcpServerName}'`, 400, {+ throw new McpConnectionError(`Failed to start OAuth authorization for MCP server '${params.mcpServerName}'`, 424, {cause: error instanceof Error ? error : undefined,});}diff --git a/packages/server/src/routes/mcpServerRoutes.ts b/packages/server/src/routes/mcpServerRoutes.tsindex ca4e9554f..8c76da4f9 100644--- a/packages/server/src/routes/mcpServerRoutes.ts+++ b/packages/server/src/routes/mcpServerRoutes.ts@@ -120,6 +120,10 @@ export const putMcpServerRoute = createRoute({content: { 'application/json': { schema: RequestErrorResponseSchema } },description: 'Invalid request body.',},+ 422: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'The server cannot satisfy `auth.type: dcr` (e.g. it advertises no registration_endpoint).',+ },},});@@ -196,12 +200,20 @@ export const authorizeMcpServerRoute = createRoute({},400: {content: { 'application/json': { schema: RequestErrorResponseSchema } },- description: 'DCR or authorize URL construction failed (e.g. server lacks registration_endpoint).',+ description: 'Invalid redirect_url.',},404: {content: { 'application/json': { schema: RequestErrorResponseSchema } },description: 'MCP server not found.',},+ 422: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'DCR could not be completed for this server (e.g. it lacks a registration_endpoint).',+ },+ 424: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'The authorization server failed dynamic client registration or authorization startup.',+ },500: {content: { 'application/json': { schema: RequestErrorResponseSchema } },description: 'Server misconfiguration (e.g. PUBLIC_BASE_URL unset).',diff --git a/packages/server/src/routes/sessionRoutes.ts b/packages/server/src/routes/sessionRoutes.tsindex 6d1dcd890..942bd4ceb 100644--- a/packages/server/src/routes/sessionRoutes.ts+++ b/packages/server/src/routes/sessionRoutes.ts@@ -122,7 +122,7 @@ export const updateSessionRoute = createRoute({},400: {content: { 'application/json': { schema: RequestErrorResponseSchema } },- description: 'Invalid request body, or named session rejected an agent update.',+ description: 'Invalid request body.',},404: {content: { 'application/json': { schema: RequestErrorResponseSchema } },@@ -131,7 +131,7 @@ export const updateSessionRoute = createRoute({422: {content: { 'application/json': { schema: RequestErrorResponseSchema } },description:- 'The agent spec is valid but references a resource this server does not provide (e.g. model, MCP server, skill, or sandbox).',+ 'Named session rejected an agent update, or the agent spec references a resource this server does not provide (e.g. model, MCP server, skill, or sandbox).',},},});diff --git a/packages/server/src/routes/turnRoutes.ts b/packages/server/src/routes/turnRoutes.tsindex b3872521f..4e1e86402 100644--- a/packages/server/src/routes/turnRoutes.ts+++ b/packages/server/src/routes/turnRoutes.ts@@ -208,7 +208,10 @@ Use \`previous_turn_id\` to chain to the session's last turn (defaults to \`auto422: {content: { 'application/json': { schema: RequestErrorResponseSchema } },description:- 'The session is valid but a required resource is no longer available (e.g. named agent, model, MCP server, skill, or sandbox provider).',+ 'The request is well-formed but cannot be processed: a referenced resource is missing ' ++ '(named agent, model, MCP server, skill, or sandbox provider), sandbox is required but ' ++ 'unavailable (e.g. file uploads), or the turn input conflicts with current state ' ++ '(e.g. unresolved tool calls or approvals, tool name collision).',},},});diff --git a/packages/server/tests/unit/apis/mcpServers.test.ts b/packages/server/tests/unit/apis/mcpServers.test.tsindex 2895f0f35..e2cb156fc 100644--- a/packages/server/tests/unit/apis/mcpServers.test.ts+++ b/packages/server/tests/unit/apis/mcpServers.test.ts@@ -236,6 +236,61 @@ describe('mcp-servers routers', () => {expect(missing.status).toBe(404);});+ it('GET /{name}/authorize returns 424 when upstream DCR registration fails', async () => {+ const asOrigin = 'https://auth-failure.example.com';+ const mcpUrl = 'https://mcp-failure.example.com/sse';+ const realFetch = globalThis.fetch;+ globalThis.fetch = (async input => {+ const url = String(input);+ if (url.includes('oauth-protected-resource')) {+ return new Response(JSON.stringify({ resource: mcpUrl, authorization_servers: [asOrigin] }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ });+ }+ if (url.includes('oauth-authorization-server') || url.includes('openid-configuration')) {+ return new Response(+ JSON.stringify({+ issuer: asOrigin,+ authorization_endpoint: `${asOrigin}/authorize`,+ token_endpoint: `${asOrigin}/token`,+ registration_endpoint: `${asOrigin}/register`,+ response_types_supported: ['code'],+ code_challenge_methods_supported: ['S256'],+ grant_types_supported: ['authorization_code', 'refresh_token'],+ token_endpoint_auth_methods_supported: ['client_secret_post', 'none'],+ }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ );+ }+ if (url.includes('/register')) {+ return new Response('upstream unavailable', { status: 500 });+ }+ return new Response(`unexpected url: ${url}`, { status: 404 });+ }) as typeof fetch;++ try {+ const put = await settingsRouter.request(+ '/',+ putInit({+ type: 'remote',+ name: 'failing-oauth-mcp',+ url: mcpUrl,+ auth: { type: 'dcr' },+ }),+ );+ expect(put.status).toBe(200);++ const authorize = await mcpServersRouter.request('/failing-oauth-mcp/authorize');+ expect(authorize.status).toBe(424);+ expect(await authorize.json()).toEqual({+ error: { message: "Failed to dynamically register OAuth client for MCP server 'failing-oauth-mcp'" },+ });+ } finally {+ globalThis.fetch = realFetch;+ }+ });+it('GET /{name}/authorize for DCR returns auth_required with an authorization_url', async () => {const asOrigin = 'https://auth.example.com';const mcpUrl = 'https://mcp.example.com/sse';diff --git a/packages/server/tests/unit/apis/sessionHttp.test.ts b/packages/server/tests/unit/apis/sessionHttp.test.tsindex 295f1e934..29bfa3119 100644--- a/packages/server/tests/unit/apis/sessionHttp.test.ts+++ b/packages/server/tests/unit/apis/sessionHttp.test.ts@@ -158,7 +158,7 @@ describe('sessions HTTP agent binding', () => {`/${json.data.id}`,jsonInit('PATCH', { agent: { type: 'value', agent_spec: { ...draftSpec, instructions: 'nope' } } }),);- expect(patchNamed.status).toBe(400);+ expect(patchNamed.status).toBe(422);});it('allows PATCH agent_spec on draft sessions', async () => {diff --git a/packages/server/tests/unit/apis/turnHarnessErrorStatus.test.ts b/packages/server/tests/unit/apis/turnHarnessErrorStatus.test.tsnew file mode 100644index 000000000..ac2d31014--- /dev/null+++ b/packages/server/tests/unit/apis/turnHarnessErrorStatus.test.ts@@ -0,0 +1,90 @@+import { OpenAPIHono } from '@hono/zod-openapi';+import type { Sessions } from '@truefoundry/utils-core/agent-session';+import { AgentHarnessError } from '@truefoundry/utils-core/core';+import { createLogger } from 'winston';+import { createTurnsRouter } from '../../../src/apis/turns';+import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';+import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';+import { createSqliteDb } from '../../../src/db/sqlite/client';+import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';+import { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';+import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';+import { SqliteSessionStore } from '../../../src/db/sqlite/session-store/SqliteSessionStore';+import { SqliteSkillStore } from '../../../src/db/sqlite/skill-store/SqliteSkillStore';+import { SqliteOAuthTokenStore } from '../../../src/db/sqlite/token-store/SqliteOAuthTokenStore';+import { ActiveTurnRegistry } from '../../../src/runtime/activeTurns';+import { EventSubscriptionRegistry } from '../../../src/runtime/event-subscription/index.js';++async function postTurnRejectingWith(error: AgentHarnessError): Promise<Response> {+ const db = createSqliteDb(':memory:');+ await migrateSqliteToLatest(db);+ const modelProviderStore = new SqliteModelProviderStore(db);+ await modelProviderStore.upsertProvider({+ tenant_id: 'default',+ manifest: {+ type: 'custom',+ name: 'test-provider',+ base_url: 'https://llm.test.example.com/v1',+ auth: { api_key: 'sk-test' },+ models: [+ {+ model_id: 'test-model',+ name: 'test-model',+ properties: { context_length: 128000, max_output_tokens: 4096 },+ },+ ],+ },+ });++ const sessions = {+ get: () =>+ Promise.resolve({+ agent_spec: { model: { name: 'test-provider/test-model' } },+ record: { last_turn_id: null },+ createTurn: () => Promise.reject(error),+ }),+ } as unknown as Sessions;++ const app = new OpenAPIHono();+ app.onError((_error, c) => c.json({ error: { message: 'Internal server error' } }, 500));+ app.route(+ '/',+ createTurnsRouter({+ sessions,+ sessionStore: new SqliteSessionStore(db),+ activeTurns: new ActiveTurnRegistry(),+ modelProviderStore,+ mcpServerStore: new SqliteMcpServerStore(db),+ tokenStore: new SqliteOAuthTokenStore(db),+ skillStore: new SqliteSkillStore(db),+ agentStore: new SqliteAgentStore(db),+ eventSubscriptions: new EventSubscriptionRegistry(undefined),+ sandboxProviderStore: new SqliteSandboxProviderStore(db),+ logger: createLogger({ silent: true }),+ }),+ );++ return app.request('/s1/turns', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: '{}',+ });+}++describe('harness rejections on POST /{session_id}/turns', () => {+ it.each([+ ['agent_sandbox_required', 422],+ ['invalid_send_input', 422],+ ['tool_name_collision', 422],+ ['invalid_file_input', 400],+ ] as const)('maps %s to %i', async (code, status) => {+ const response = await postTurnRejectingWith(new AgentHarnessError(code, 'rejected'));+ expect(response.status).toBe(status);+ expect(await response.json()).toEqual({ error: { message: 'rejected' } });+ });++ it('keeps capability state failures as internal errors', async () => {+ const response = await postTurnRejectingWith(new AgentHarnessError('capability_state_error', 'rejected'));+ expect(response.status).toBe(500);+ });+});diff --git a/packages/server/tests/unit/mcp/auth/mcpOAuth.test.ts b/packages/server/tests/unit/mcp/auth/mcpOAuth.test.tsindex 8a775eef8..dbac8edbf 100644--- a/packages/server/tests/unit/mcp/auth/mcpOAuth.test.ts+++ b/packages/server/tests/unit/mcp/auth/mcpOAuth.test.ts@@ -244,6 +244,19 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {expect((registerBodies[1] as Record<string, unknown>)['token_endpoint_auth_method']).toBeUndefined();});+ it('rejects registration responses without client_id as failed dependencies', async () => {+ stubOauthFetch({ registeredClient: { client_id: '' } });++ await expect(+ createMcpOAuthClient({+ mcpServerUrl: SERVER_URL,+ mcpServerName: SERVER_NAME,+ redirectUri: mcpOAuthCallbackUrl(),+ clientName: CLIENT_NAME,+ }),+ ).rejects.toMatchObject({ name: 'McpConnectionError', statusCode: 424 });+ });+it('does not retry registration on non-metadata failures', async () => {const { mcpServerStore } = newStores();const { registerCallCount } = stubOauthFetch({@@ -258,7 +271,7 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {mcpServerName: SERVER_NAME,clientName: CLIENT_NAME,}),- ).rejects.toBeInstanceOf(McpConnectionError);+ ).rejects.toMatchObject({ name: 'McpConnectionError', statusCode: 424 });expect(registerCallCount()).toBe(1);});@@ -291,7 +304,7 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {redirectUri: mcpOAuthCallbackUrl(),clientName: CLIENT_NAME,}),- ).rejects.toBeInstanceOf(McpConnectionError);+ ).rejects.toMatchObject({ name: 'McpConnectionError', statusCode: 424 });expect(registerCallCount()).toBe(2);expect(await mcpServerStore.getClient({ id: SERVER_ID })).toBeUndefined();});@@ -407,6 +420,7 @@ describe('buildMcpAuthorizationUrl', () => {).rejects.toMatchObject({name: 'McpConnectionError',message: expect.stringContaining('Failed to start OAuth authorization'),+ statusCode: 424,});});});