mirror of
https://github.com/simstudioai/sim.git
synced 2026-11-21 20:57:55 +08:00
fix(v2): stop a third-party tool description from 500ing MCP discovery
`v2McpToolInputSchema` declared `description: z.string().optional()` inside a `.catchall(z.unknown())` object, and a declared key beats the catchall. The MCP SDK's own `ToolSchema.inputSchema` does not declare `description` at all, so any value — including the JSON `null` a Python server emits for an absent one — passes its validation and reaches Sim unchecked. The builder's outbound `.parse()` then threw, and the discovery error policy correctly declines to classify a Sim-side schema defect, so the endpoint that completes MCP onboarding answered a bare 500. The key is dropped and left to the catchall; `type`, `properties`, and `required` stay pinned because the SDK enforces those at least as tightly. Also in the v2 resources family: - The single-resource query schemas for MCP servers, skills, custom tools, and secrets are now `.strict()`, matching every list in the same family. A mistyped flag was silently ignored behind a 200. - `openapi/resources.ts` re-derived `RESOURCE_ERRORS` and `RESOURCE_CONFLICT_ERRORS` inline in 21 of 22 operations. They now import the shared constants; the generated spec is unchanged, which is the point. - The internal MCP refresh route stamped `updatedAt` alongside `lastToolsRefresh`. `updatedAt` means "configuration last changed" and is a public keyset sort, so a refresh moved rows out from under an in-flight page. `updateServerStatus` already held that invariant; the route now matches it. - The discovery cooldown is a typed `McpServerCooldownError` rather than a substring search for `cooldown`. `McpConnectionError` interpolates the server's display name into its message, so a server named after the word was reported as a transient cooldown when its connection had genuinely failed.
This commit is contained in:
1 parent
1faac4e8ef
commit
cd3efefab9
21 files changed
+407
-56
No files matched your search
@@ -3019,10 +3019,6 @@
|
||||
"type": "string",
|
||||
"description": "Name of a required argument."
|
||||
}
|
||||
},
|
||||
"description": {
|
||||
"description": "Description of the argument object.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["type"],
|
||||
|
||||
@@ -98,6 +98,35 @@ describe('MCP server refresh route', () => {
|
||||
)
|
||||
})
|
||||
|
||||
/**
|
||||
* `updatedAt` means "when the server's configuration last changed" and is one
|
||||
* of the public list's keyset sorts, so a refresh must not stamp it. The
|
||||
* service's discovery status write already holds that invariant; this route
|
||||
* writes the same row from the UI's refresh button, and stamping it here moves
|
||||
* the row to the head of `sortBy=updatedAt` under an in-flight v2 page, which
|
||||
* duplicates some servers across pages and skips others. Liveness is published
|
||||
* through `lastToolsRefresh`, `lastConnected`, and `lastError`.
|
||||
*/
|
||||
it('records the refresh without stamping updatedAt', async () => {
|
||||
mockDiscoverServerTools.mockResolvedValueOnce([])
|
||||
|
||||
const request = new Request('http://localhost/api/mcp/servers/server-1/refresh', {
|
||||
method: 'POST',
|
||||
}) as NextRequest
|
||||
await POST(request, { params: Promise.resolve({ id: 'server-1' }) })
|
||||
|
||||
const refreshWrites = dbChainMockFns.set.mock.calls.filter(
|
||||
([values]) => (values as Record<string, unknown>)?.lastToolsRefresh !== undefined
|
||||
)
|
||||
expect(refreshWrites.length).toBeGreaterThan(0)
|
||||
for (const [values] of refreshWrites) {
|
||||
expect(
|
||||
(values as Record<string, unknown>).updatedAt,
|
||||
'the refresh route stamped updatedAt, corrupting the updatedAt keyset page'
|
||||
).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('reports the discovery failure when status persistence leaves a stale connected row', async () => {
|
||||
const reflectedSecret = 'Bearer reflected-static-token'
|
||||
mockDiscoverServerTools.mockRejectedValueOnce(
|
||||
|
||||
@@ -229,11 +229,20 @@ export const POST = withRouteHandler(
|
||||
|
||||
const now = new Date()
|
||||
|
||||
/**
|
||||
* Deliberately leaves `updatedAt` alone, matching the invariant
|
||||
* `McpService.updateServerStatus` holds: `updatedAt` means "when the
|
||||
* server's configuration last changed", and it is one of the public
|
||||
* list's keyset sorts. A refresh stamping it moves the row to the head
|
||||
* of `sortBy=updatedAt` under an in-flight page, so a caller walking the
|
||||
* list while anyone presses this button sees servers duplicated across
|
||||
* pages and others skipped. Refresh liveness is already published
|
||||
* through `lastToolsRefresh`, `lastConnected`, and `lastError`.
|
||||
*/
|
||||
const [refreshedServer] = await db
|
||||
.update(mcpServers)
|
||||
.set({
|
||||
lastToolsRefresh: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
|
||||
@@ -134,6 +134,32 @@ describe('GET /api/v2/credentials', () => {
|
||||
expect(JSON.stringify(body)).not.toContain('createdBy')
|
||||
})
|
||||
|
||||
/**
|
||||
* The projection is an explicit field-by-field copy, which is what makes a
|
||||
* column added to the credential table later inert here: a field nobody wrote
|
||||
* into `toV2Credential` is simply never read. The outbound response `.parse()`
|
||||
* strips whatever survives, so a leak needs two independent mistakes. This
|
||||
* pins the pairing against a row carrying a column the projection has never
|
||||
* heard of.
|
||||
*/
|
||||
it('withholds a credential column the projection was never taught to publish', async () => {
|
||||
mocks.execute.mockResolvedValueOnce({
|
||||
credentials: [{ ...credential, encryptedFutureSecret: 'MUST_NOT_LEAK_EITHER' }],
|
||||
nextCursorKeys: null,
|
||||
sortBy: 'createdAt',
|
||||
sortOrder: 'desc',
|
||||
})
|
||||
|
||||
const response = await GET(
|
||||
new NextRequest(`http://localhost:3000/api/v2/credentials?workspaceId=${WORKSPACE_ID}`)
|
||||
)
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(JSON.stringify(body)).not.toContain('encryptedFutureSecret')
|
||||
expect(JSON.stringify(body)).not.toContain('MUST_NOT_LEAK_EITHER')
|
||||
})
|
||||
|
||||
it('hides repository errors that may contain secret details', async () => {
|
||||
mocks.execute.mockRejectedValueOnce(new Error('encryptedServiceAccountKey failed'))
|
||||
|
||||
|
||||
@@ -130,6 +130,25 @@ describe('/api/v2/custom-tools/[id]', () => {
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Every list in this family rejects a query param it does not implement, so
|
||||
* the single-resource reads must too. A caller who mistypes a flag otherwise
|
||||
* gets a 200 that silently ignored it, which reads as confirmation the flag
|
||||
* exists and does nothing.
|
||||
*/
|
||||
it('rejects a query param it does not implement', async () => {
|
||||
const response = await GET(
|
||||
new NextRequest(
|
||||
`http://localhost:3000/api/v2/custom-tools/${tool.id}?workspaceId=${WORKSPACE_ID}&includeCodes=true`,
|
||||
{ method: 'GET', headers: { 'x-api-key': 'key' } }
|
||||
),
|
||||
context
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mocks.get).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('updates a custom tool through its semantic update operation', async () => {
|
||||
const response = await PATCH(
|
||||
request('PATCH', { workspaceId: WORKSPACE_ID, code: 'return 2' }),
|
||||
|
||||
@@ -121,6 +121,25 @@ describe('/api/v2/mcp-servers/[id]', () => {
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Every list in this family rejects a query param it does not implement, so
|
||||
* the single-resource reads must too. A caller who mistypes a flag otherwise
|
||||
* gets a 200 that silently ignored it, which reads as confirmation the flag
|
||||
* exists and does nothing.
|
||||
*/
|
||||
it('rejects a query param it does not implement', async () => {
|
||||
const response = await GET(
|
||||
new NextRequest(
|
||||
`http://localhost:3000/api/v2/mcp-servers/${server.id}?workspaceId=${WORKSPACE_ID}&includeTools=true`,
|
||||
{ method: 'GET', headers: { 'x-api-key': 'key' } }
|
||||
),
|
||||
context
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mocks.get).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('updates an MCP server through the strict semantic update operation', async () => {
|
||||
const response = await PATCH(
|
||||
request('PATCH', { workspaceId: WORKSPACE_ID, name: 'New docs' }),
|
||||
|
||||
@@ -36,7 +36,11 @@ vi.mock('@/lib/mcp/application/use-cases', () => ({
|
||||
}))
|
||||
|
||||
import { WorkspaceApiKeyAuthorizationError } from '@/lib/core/application'
|
||||
import { McpConnectionError, McpOauthAuthorizationRequiredError } from '@/lib/mcp/types'
|
||||
import {
|
||||
McpConnectionError,
|
||||
McpOauthAuthorizationRequiredError,
|
||||
McpServerCooldownError,
|
||||
} from '@/lib/mcp/types'
|
||||
import { GET } from '@/app/api/v2/mcp-servers/[id]/tools/route'
|
||||
|
||||
const WORKSPACE_ID = 'workspace-1'
|
||||
@@ -173,6 +177,63 @@ describe('/api/v2/mcp-servers/[id]/tools', () => {
|
||||
expect(body.error.code).toBe('INTERNAL_ERROR')
|
||||
})
|
||||
|
||||
/**
|
||||
* `inputSchema` below the `object` wrapper is authored by the third-party
|
||||
* server, and the MCP SDK's own `ToolSchema` does not declare `description`
|
||||
* there — its `.catchall(z.unknown())` lets any value through, so a server
|
||||
* serializing an absent description as JSON `null` (what a Python `None`
|
||||
* produces) reaches Sim unvalidated. Declaring the key more tightly than the
|
||||
* upstream schema does made the builder's outbound `.parse()` throw, and
|
||||
* discovery answered a bare 500 for a payload the protocol permits.
|
||||
*/
|
||||
it('publishes a tool whose server reported a non-string inputSchema description', async () => {
|
||||
mocks.discover.mockResolvedValueOnce({
|
||||
tools: [
|
||||
{
|
||||
...TOOL,
|
||||
inputSchema: { type: 'object' as const, description: null, properties: {} },
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const response = await GET(request(`workspaceId=${WORKSPACE_ID}`), { ...context })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.data[0].inputSchema).toEqual({
|
||||
type: 'object',
|
||||
description: null,
|
||||
properties: {},
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* The 503 wording used to be selected by searching the error message for
|
||||
* `cooldown`. `McpConnectionError` interpolates the server's display name into
|
||||
* that message, so a server the caller happened to name after the word
|
||||
* borrowed the negative-cache wording and told them to wait out a cooldown
|
||||
* that was never entered.
|
||||
*/
|
||||
it('does not read cooldown wording out of a server display name', async () => {
|
||||
mocks.discover.mockRejectedValueOnce(new McpConnectionError('ECONNREFUSED', 'Cooldown Docs'))
|
||||
|
||||
const response = await GET(request(`workspaceId=${WORKSPACE_ID}`), { ...context })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(503)
|
||||
expect(body.error.message).toBe('The MCP server could not be reached')
|
||||
})
|
||||
|
||||
it('reports a server inside the discovery cooldown with its own wording', async () => {
|
||||
mocks.discover.mockRejectedValueOnce(new McpServerCooldownError(SERVER_ID))
|
||||
|
||||
const response = await GET(request(`workspaceId=${WORKSPACE_ID}`), { ...context })
|
||||
const body = await response.json()
|
||||
|
||||
expect(response.status).toBe(503)
|
||||
expect(body.error.message).toBe('The MCP server recently failed and is in cooldown')
|
||||
})
|
||||
|
||||
it('rejects a workspace API key, which cannot supply the caller`s OAuth grant', async () => {
|
||||
mocks.discover.mockRejectedValueOnce(new WorkspaceApiKeyAuthorizationError())
|
||||
|
||||
|
||||
@@ -6,7 +6,11 @@ import { createV2ResourceConcealmentPolicy, type V2ErrorPolicy } from '@/lib/api
|
||||
import { isTimeoutError } from '@/lib/core/execution-limits'
|
||||
import { projectMcpHeaders } from '@/lib/mcp/projection'
|
||||
import type { McpServerRow } from '@/lib/mcp/queries'
|
||||
import { McpConnectionError, McpOauthAuthorizationRequiredError } from '@/lib/mcp/types'
|
||||
import {
|
||||
McpConnectionError,
|
||||
McpOauthAuthorizationRequiredError,
|
||||
McpServerCooldownError,
|
||||
} from '@/lib/mcp/types'
|
||||
import { v2Error } from '@/app/api/v2/lib/response'
|
||||
|
||||
/**
|
||||
@@ -49,10 +53,15 @@ export const MCP_SERVER_REAUTHORIZATION_REQUIRED = 'MCP_SERVER_REAUTHORIZATION_R
|
||||
*
|
||||
* Every branch returns a constant, so an upstream message — which may quote a
|
||||
* hostname, a token endpoint, or a stack — never reaches the caller.
|
||||
*
|
||||
* Selection is typed for the same reason classification is. The cooldown branch
|
||||
* used to search the message for `cooldown`, but `McpConnectionError`
|
||||
* interpolates the server's display name into its message, so a server a caller
|
||||
* named after the word was told to wait out a cooldown it was never in.
|
||||
*/
|
||||
function unreachableServerMessage(error: unknown): string {
|
||||
if (isTimeoutError(error)) return 'The MCP server took too long to respond'
|
||||
if (error instanceof McpConnectionError && error.message.toLowerCase().includes('cooldown')) {
|
||||
if (error instanceof McpServerCooldownError) {
|
||||
return 'The MCP server recently failed and is in cooldown'
|
||||
}
|
||||
return 'The MCP server could not be reached'
|
||||
|
||||
@@ -157,6 +157,25 @@ describe('/api/v2/secrets/[name]', () => {
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* The secrets list rejects a query param it does not implement, so the delete
|
||||
* must too. A caller who mistypes `scope` otherwise gets a 400 for the missing
|
||||
* required param — but a caller who adds a param that does not exist at all
|
||||
* would have had it silently ignored.
|
||||
*/
|
||||
it('rejects a query param it does not implement', async () => {
|
||||
const response = await DELETE(
|
||||
new NextRequest(
|
||||
`http://localhost:3000/api/v2/secrets/${SECRET_NAME}?workspaceId=${WORKSPACE_ID}&scope=workspace&scopes=personal`,
|
||||
{ method: 'DELETE', headers: { 'x-api-key': 'key' } }
|
||||
),
|
||||
context
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mocks.remove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('renders typed application errors without leaking raw errors', async () => {
|
||||
mocks.remove.mockRejectedValueOnce(new OrchestrationError('not_found', 'stored detail'))
|
||||
|
||||
|
||||
@@ -124,6 +124,25 @@ describe('/api/v2/skills/[id]', () => {
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* Every list in this family rejects a query param it does not implement, so
|
||||
* the single-resource reads must too. A caller who mistypes a flag otherwise
|
||||
* gets a 200 that silently ignored it, which reads as confirmation the flag
|
||||
* exists and does nothing.
|
||||
*/
|
||||
it('rejects a query param it does not implement', async () => {
|
||||
const response = await GET(
|
||||
new NextRequest(
|
||||
`http://localhost:3000/api/v2/skills/${skill.id}?workspaceId=${WORKSPACE_ID}&includeContents=true`,
|
||||
{ method: 'GET', headers: { 'x-api-key': 'key' } }
|
||||
),
|
||||
context
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mocks.get).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('updates a skill and emits only surface analytics', async () => {
|
||||
const response = await PATCH(
|
||||
request('PATCH', { workspaceId: WORKSPACE_ID, content: '# Updated' }),
|
||||
|
||||
@@ -179,6 +179,50 @@ describe('/api/v2/skills', () => {
|
||||
expect(mocks.list).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
/**
|
||||
* `search` and `sortOrder` change the sequence the offset counts positions in
|
||||
* just as `sortBy` does, so both are stamped into the scope and both must
|
||||
* invalidate a replayed cursor.
|
||||
*/
|
||||
it.each([
|
||||
['search', 'search=other'],
|
||||
['sortOrder', 'sortOrder=asc'],
|
||||
])('rejects a cursor replayed under a different %s', async (_field, param) => {
|
||||
const cursor = Buffer.from(JSON.stringify({ scope: SCOPE(), offset: 2 })).toString('base64')
|
||||
|
||||
const response = await GET(
|
||||
request(
|
||||
'GET',
|
||||
`/api/v2/skills?workspaceId=${WORKSPACE_ID}&${param}&cursor=${encodeURIComponent(cursor)}`
|
||||
)
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(mocks.list).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
/**
|
||||
* `limit` is deliberately absent from the scope: it selects how much of the
|
||||
* sequence to return, not what the sequence is. Stamping it would strand every
|
||||
* cursor the moment a caller changed page size, for no correctness gain.
|
||||
*/
|
||||
it('resumes a cursor minted under a different page size', async () => {
|
||||
mocks.list.mockResolvedValueOnce({ skills: [skill], hasMore: false, offset: 2, limit: 5 })
|
||||
const cursor = Buffer.from(JSON.stringify({ scope: SCOPE(), offset: 2 })).toString('base64')
|
||||
|
||||
const response = await GET(
|
||||
request(
|
||||
'GET',
|
||||
`/api/v2/skills?workspaceId=${WORKSPACE_ID}&limit=5&cursor=${encodeURIComponent(cursor)}`
|
||||
)
|
||||
)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(mocks.list).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ input: expect.objectContaining({ limit: 5, offset: 2 }) })
|
||||
)
|
||||
})
|
||||
|
||||
/**
|
||||
* The guard itself is unit-tested in `definition.test.ts`; this proves the
|
||||
* pairing end-to-end, on a real v2 read that used to reply 500 to a plain HEAD.
|
||||
|
||||
@@ -110,9 +110,11 @@ export const v2CustomToolParamsSchema = z.object({
|
||||
})
|
||||
export type V2CustomToolParams = z.output<typeof v2CustomToolParamsSchema>
|
||||
|
||||
export const v2CustomToolWorkspaceQuerySchema = z.object({
|
||||
workspaceId: workspaceIdSchema.describe('Workspace that owns the custom tool.'),
|
||||
})
|
||||
export const v2CustomToolWorkspaceQuerySchema = z
|
||||
.object({
|
||||
workspaceId: workspaceIdSchema.describe('Workspace that owns the custom tool.'),
|
||||
})
|
||||
.strict()
|
||||
export type V2CustomToolWorkspaceQuery = z.output<typeof v2CustomToolWorkspaceQuerySchema>
|
||||
|
||||
/** A custom tool's natural name field is `title`, so that is what `search` matches. */
|
||||
|
||||
@@ -172,9 +172,11 @@ export const v2McpServerParamsSchema = z.object({
|
||||
})
|
||||
export type V2McpServerParams = z.output<typeof v2McpServerParamsSchema>
|
||||
|
||||
export const v2McpServerWorkspaceQuerySchema = z.object({
|
||||
workspaceId: workspaceIdSchema.describe('Workspace that owns the MCP server.'),
|
||||
})
|
||||
export const v2McpServerWorkspaceQuerySchema = z
|
||||
.object({
|
||||
workspaceId: workspaceIdSchema.describe('Workspace that owns the MCP server.'),
|
||||
})
|
||||
.strict()
|
||||
export type V2McpServerWorkspaceQuery = z.output<typeof v2McpServerWorkspaceQuerySchema>
|
||||
|
||||
export const v2McpServerSortFields = ['name', 'createdAt', 'updatedAt'] as const
|
||||
@@ -288,7 +290,18 @@ export type V2UpdateMcpServerBody = z.input<typeof v2UpdateMcpServerBodySchema>
|
||||
* declaration gives an OpenAI function's `parameters`. `type` can be pinned to
|
||||
* the literal because the MCP SDK's own `ListToolsResult` schema already rejects
|
||||
* a tool whose `inputSchema.type` is anything else, so a server cannot make this
|
||||
* response fail its own validation.
|
||||
* response fail its own validation. `properties` and `required` are pinned on
|
||||
* the same ground, and the SDK is the stricter of the two on `properties`.
|
||||
*
|
||||
* The rule that keeps this safe is that a key may only be declared here when the
|
||||
* SDK declares it at least as tightly. `description` may not: the SDK's
|
||||
* `ToolSchema.inputSchema` does not declare it at all, so its own
|
||||
* `.catchall(z.unknown())` admits any value — including the JSON `null` a Python
|
||||
* server emits for an absent description. Declaring it `z.string().optional()`
|
||||
* made the builder's outbound `.parse()` throw on a payload the protocol
|
||||
* permits, and discovery answered a bare 500. It is left to the `catchall`
|
||||
* below, which publishes as `additionalProperties` and passes the value through
|
||||
* untouched.
|
||||
*/
|
||||
const v2McpToolInputSchema = z
|
||||
.object({
|
||||
@@ -303,7 +316,6 @@ const v2McpToolInputSchema = z
|
||||
.array(z.string().describe('Name of a required argument.'))
|
||||
.optional()
|
||||
.describe('Names of the arguments the tool requires.'),
|
||||
description: z.string().optional().describe('Description of the argument object.'),
|
||||
})
|
||||
.catchall(z.unknown().describe('Additional JSON Schema keyword reported by the server.'))
|
||||
.describe("JSON Schema for the tool's arguments, as reported by the server.")
|
||||
|
||||
@@ -21,12 +21,12 @@ import {
|
||||
FULL_SET_LIST,
|
||||
RATE_LIMIT_HEADERS,
|
||||
RESOURCE_CONFLICT_ERRORS,
|
||||
RESOURCE_ERRORS,
|
||||
V2_API_KEY_SECURITY,
|
||||
V2_API_KEY_SECURITY_SCHEMES,
|
||||
V2_COMMON_HEADERS,
|
||||
V2_ERROR_SCHEMA,
|
||||
WORKSPACE_API_KEY_DENIED,
|
||||
WORKSPACE_ERRORS,
|
||||
} from '@/lib/api/contracts/v2/openapi/shared'
|
||||
import {
|
||||
v2DeleteSecretContract,
|
||||
@@ -209,7 +209,7 @@ const routes = [
|
||||
summary: 'Get Workspace',
|
||||
description:
|
||||
'Return public metadata for one accessible workspace. Governance identities, billing identities, and internal membership identifiers are intentionally omitted.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'Public workspace metadata.' },
|
||||
}),
|
||||
{
|
||||
@@ -235,7 +235,7 @@ const routes = [
|
||||
summary: 'List Workspace Members',
|
||||
description:
|
||||
"List the workspace's effective members ordered by email. Explicit workspace grants and inherited organization-administrator grants are merged; internal membership and billing identities are omitted.",
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'An email-ordered page of effective workspace members.' },
|
||||
}),
|
||||
{
|
||||
@@ -267,7 +267,7 @@ const routes = [
|
||||
summary: 'List MCP Servers',
|
||||
description:
|
||||
'List MCP servers registered in a workspace. Request-header values and OAuth client secrets are never returned. Nothing caps how many servers a workspace registers, so this list is paginated: paginate with `limit` and `cursor`, stopping when `nextCursor` is null. `connectionStatus`, `toolCount`, `lastError`, and `lastToolsRefresh` describe the most recent tool discovery and stay at their registration defaults until one runs — call `GET /api/v2/mcp-servers/{id}/tools` to run it.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'MCP servers registered in the workspace.' },
|
||||
}),
|
||||
{
|
||||
@@ -293,7 +293,7 @@ const routes = [
|
||||
summary: 'Create MCP Server',
|
||||
description:
|
||||
'Register an MCP server in a workspace. The endpoint URL determines server identity, must be absolute HTTP or HTTPS, and cannot contain environment-variable references. Header values and OAuth client secrets are write-only. `transport`, `timeout`, `retries`, and `enabled` are applied server-side when omitted; the effective values are in the response.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
|
||||
errors: RESOURCE_CONFLICT_ERRORS,
|
||||
success: { description: 'The MCP server was registered.' },
|
||||
}),
|
||||
{
|
||||
@@ -328,7 +328,7 @@ const routes = [
|
||||
summary: 'Get MCP Server',
|
||||
description:
|
||||
'Fetch one MCP server by identifier. Request-header values and OAuth client secrets are never returned.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'The MCP server.' },
|
||||
}),
|
||||
{
|
||||
@@ -360,7 +360,7 @@ const routes = [
|
||||
summary: 'Update MCP Server',
|
||||
description:
|
||||
'Update the supplied MCP server fields. The URL is immutable because it determines server identity; delete and recreate the server to change endpoints. Two fields do not follow the omitted-fields-are-retained rule. `headers` is replaced wholesale rather than merged: sending it drops every stored header it does not repeat, and the only way to keep a header is to resend it. Changing `oauthClientId`, or sending `oauthClientSecret` as null or a new value, revokes the stored OAuth grant and forces reauthorization; switching away from OAuth authentication revokes it too.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'The updated MCP server.' },
|
||||
}),
|
||||
{
|
||||
@@ -393,7 +393,7 @@ const routes = [
|
||||
summary: 'Delete MCP Server',
|
||||
description:
|
||||
"Remove an MCP server and revoke its OAuth tokens. Workflows retain blocks that referenced the server's tools, but those tools can no longer be called.",
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'The MCP server was deleted.' },
|
||||
}),
|
||||
{
|
||||
@@ -456,7 +456,7 @@ const routes = [
|
||||
summary: 'List Skills',
|
||||
description:
|
||||
'List workspace and built-in skills. Built-ins are marked read-only. The list omits skill bodies; fetch one skill to read its content. Paginate with `limit` and `cursor`, stopping when `nextCursor` is null.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'Skills available in the workspace.' },
|
||||
}),
|
||||
{
|
||||
@@ -482,7 +482,7 @@ const routes = [
|
||||
summary: 'Create Skill',
|
||||
description:
|
||||
'Create one skill in a workspace. Its kebab-case name must be unique and cannot be reserved by a built-in skill. Note that a workspace API key may create a skill but may not later update or delete it.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
|
||||
errors: RESOURCE_CONFLICT_ERRORS,
|
||||
success: { description: 'The skill was created.' },
|
||||
}),
|
||||
{
|
||||
@@ -516,7 +516,7 @@ const routes = [
|
||||
summary: 'Get Skill',
|
||||
description:
|
||||
'Fetch one workspace or built-in skill, including its full content. Built-in skills are marked read-only.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'The skill.' },
|
||||
}),
|
||||
{
|
||||
@@ -547,7 +547,7 @@ const routes = [
|
||||
operationId: 'updateSkill',
|
||||
summary: 'Update Skill',
|
||||
description: `Update the supplied fields on a workspace skill. Omitted fields retain their stored values. Built-in skills are read-only. ${WORKSPACE_API_KEY_DENIED}`,
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
|
||||
errors: RESOURCE_CONFLICT_ERRORS,
|
||||
success: { description: 'The updated skill.' },
|
||||
}),
|
||||
{
|
||||
@@ -579,7 +579,7 @@ const routes = [
|
||||
operationId: 'deleteSkill',
|
||||
summary: 'Delete Skill',
|
||||
description: `Delete a workspace skill. Built-in skills are read-only and cannot be deleted. ${WORKSPACE_API_KEY_DENIED}`,
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'The skill was deleted.' },
|
||||
}),
|
||||
{
|
||||
@@ -611,7 +611,7 @@ const routes = [
|
||||
summary: 'List Custom Tools',
|
||||
description:
|
||||
'List code-backed custom tools defined in a workspace. Legacy personal tools are excluded. Paginate with `limit` and `cursor`, stopping when `nextCursor` is null.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'Custom tools defined in the workspace.' },
|
||||
}),
|
||||
{
|
||||
@@ -637,7 +637,7 @@ const routes = [
|
||||
summary: 'Create Custom Tool',
|
||||
description:
|
||||
'Create a code-backed custom tool in a workspace. Its title must be unique because tools resolve by title at call time.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
|
||||
errors: RESOURCE_CONFLICT_ERRORS,
|
||||
success: { description: 'The custom tool was created.' },
|
||||
}),
|
||||
{
|
||||
@@ -670,7 +670,7 @@ const routes = [
|
||||
operationId: 'getCustomTool',
|
||||
summary: 'Get Custom Tool',
|
||||
description: 'Fetch one custom tool by identifier, scoped to its workspace.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'The custom tool.' },
|
||||
}),
|
||||
{
|
||||
@@ -702,7 +702,7 @@ const routes = [
|
||||
summary: 'Update Custom Tool',
|
||||
description:
|
||||
'Update the supplied custom tool fields. Omitted fields retain their stored values, and titles must remain unique within the workspace.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound', 'Conflict'],
|
||||
errors: RESOURCE_CONFLICT_ERRORS,
|
||||
success: { description: 'The updated custom tool.' },
|
||||
}),
|
||||
{
|
||||
@@ -735,7 +735,7 @@ const routes = [
|
||||
summary: 'Delete Custom Tool',
|
||||
description:
|
||||
'Delete a custom tool. Agent blocks retain their configuration but can no longer call the deleted tool.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'The custom tool was deleted.' },
|
||||
}),
|
||||
{
|
||||
@@ -767,7 +767,7 @@ const routes = [
|
||||
summary: 'List Credentials',
|
||||
description:
|
||||
'List OAuth and service-account connections visible to the caller. Secret material is never returned. Credential mutations and single-resource reads are intentionally not exposed. Paginate with `limit` and `cursor`, stopping when `nextCursor` is null.',
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'Credentials visible to the caller.' },
|
||||
}),
|
||||
{
|
||||
@@ -792,7 +792,7 @@ const routes = [
|
||||
operationId: 'listSecrets',
|
||||
summary: 'List Secrets',
|
||||
description: `List workspace and caller-owned personal secret metadata. Only names, scope, role, and timestamps are returned; secret values are never read or returned. Paginate with \`limit\` and \`cursor\`, stopping when \`nextCursor\` is null. ${WORKSPACE_API_KEY_DENIED}`,
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'Secret metadata visible to the caller.' },
|
||||
}),
|
||||
{
|
||||
@@ -817,7 +817,7 @@ const routes = [
|
||||
operationId: 'setSecret',
|
||||
summary: 'Set Secret',
|
||||
description: `Create or replace a workspace or caller-owned personal secret. The value is encrypted at rest, is write-only, and is never included in the response. ${WORKSPACE_API_KEY_DENIED}`,
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: {
|
||||
byStatus: {
|
||||
200: { description: 'The existing secret value was replaced.' },
|
||||
@@ -860,7 +860,7 @@ const routes = [
|
||||
operationId: 'deleteSecret',
|
||||
summary: 'Delete Secret',
|
||||
description: `Delete a workspace or caller-owned personal secret without reading or returning its stored value. ${WORKSPACE_API_KEY_DENIED}`,
|
||||
errors: [...WORKSPACE_ERRORS, 'NotFound'],
|
||||
errors: RESOURCE_ERRORS,
|
||||
success: { description: 'The secret was deleted.' },
|
||||
}),
|
||||
{
|
||||
|
||||
@@ -88,10 +88,12 @@ export const v2SetSecretBodySchema = z
|
||||
.strict()
|
||||
export type V2SetSecretBody = z.input<typeof v2SetSecretBodySchema>
|
||||
|
||||
export const v2DeleteSecretQuerySchema = z.object({
|
||||
workspaceId: workspaceIdSchema.describe('Workspace in which the secret is available.'),
|
||||
scope: v2SecretScopeSchema,
|
||||
})
|
||||
export const v2DeleteSecretQuerySchema = z
|
||||
.object({
|
||||
workspaceId: workspaceIdSchema.describe('Workspace in which the secret is available.'),
|
||||
scope: v2SecretScopeSchema,
|
||||
})
|
||||
.strict()
|
||||
export type V2DeleteSecretQuery = z.output<typeof v2DeleteSecretQuerySchema>
|
||||
|
||||
/**
|
||||
|
||||
@@ -88,9 +88,11 @@ export const v2SkillParamsSchema = z.object({
|
||||
})
|
||||
export type V2SkillParams = z.output<typeof v2SkillParamsSchema>
|
||||
|
||||
export const v2SkillWorkspaceQuerySchema = z.object({
|
||||
workspaceId: workspaceIdSchema.describe('Workspace that owns the skill.'),
|
||||
})
|
||||
export const v2SkillWorkspaceQuerySchema = z
|
||||
.object({
|
||||
workspaceId: workspaceIdSchema.describe('Workspace that owns the skill.'),
|
||||
})
|
||||
.strict()
|
||||
export type V2SkillWorkspaceQuery = z.output<typeof v2SkillWorkspaceQuerySchema>
|
||||
|
||||
export const v2SkillSortFields = ['name', 'createdAt', 'updatedAt'] as const
|
||||
|
||||
@@ -162,6 +162,57 @@ describe('MCP server application use cases', () => {
|
||||
expect(mocks.effects).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
/**
|
||||
* A server id is derived from the workspace and endpoint URL, so re-registering
|
||||
* a URL that was soft-deleted reuses the same row. That is a create from the
|
||||
* caller's side — the resource they asked for did not exist a moment ago — so it
|
||||
* must succeed with the create's 201 rather than collide with its own tombstone.
|
||||
* The conflict guard therefore keys on the id state's `deleted` flag, not on
|
||||
* whether the writer reported an update.
|
||||
*/
|
||||
it('creates over a soft-deleted registration rather than colliding with its tombstone', async () => {
|
||||
mocks.idState.mockResolvedValueOnce({ deleted: true })
|
||||
mocks.create.mockResolvedValueOnce({
|
||||
success: true,
|
||||
serverId: server.id,
|
||||
server,
|
||||
updated: true,
|
||||
})
|
||||
|
||||
const result = await createMcpServerUseCase.execute({
|
||||
principal: { kind: 'session', userId: 'user-1', sessionId: 'session-1' },
|
||||
input: { workspaceId: workspace.workspaceId, name: server.name, url: server.url },
|
||||
})
|
||||
|
||||
expect(result.server.id).toBe(server.id)
|
||||
expect(mocks.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ existingServerBehavior: 'reject' })
|
||||
)
|
||||
expect(events).toEqual(['audit', 'effects'])
|
||||
})
|
||||
|
||||
/**
|
||||
* The pre-check reads the id state outside the write, so two concurrent creates
|
||||
* of the same URL can both pass it. The unique index is what actually decides,
|
||||
* and its `23505` must surface as the same conflict the pre-check reports —
|
||||
* otherwise the loser of the race gets a 500 for a condition the API defines.
|
||||
*/
|
||||
it('reports the unique-index loser of a concurrent create as a conflict', async () => {
|
||||
mocks.create.mockRejectedValueOnce(
|
||||
Object.assign(new Error('duplicate key value violates unique constraint'), { code: '23505' })
|
||||
)
|
||||
|
||||
await expect(
|
||||
createMcpServerUseCase.execute({
|
||||
principal: { kind: 'session', userId: 'user-1', sessionId: 'session-1' },
|
||||
input: { workspaceId: workspace.workspaceId, name: server.name, url: server.url },
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'conflict' })
|
||||
|
||||
expect(mocks.audit).not.toHaveBeenCalled()
|
||||
expect(mocks.effects).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects workspace-key tool discovery before protected loading', async () => {
|
||||
await expect(
|
||||
discoverMcpToolsUseCase.execute({
|
||||
|
||||
@@ -31,9 +31,9 @@ import {
|
||||
type McpCacheStorageAdapter,
|
||||
} from '@/lib/mcp/storage'
|
||||
import {
|
||||
McpConnectionError,
|
||||
McpOauthAuthorizationRequiredError,
|
||||
type McpServerConfig,
|
||||
McpServerCooldownError,
|
||||
type McpServerStatusConfig,
|
||||
type McpServerSummary,
|
||||
type McpTool,
|
||||
@@ -1060,10 +1060,7 @@ class McpService {
|
||||
|
||||
if (refresh !== 'force' && (await this.isServerUnhealthy(workspaceId, serverId))) {
|
||||
logger.info(`[${requestId}] Skipping recently-failed server ${serverId} (negative-cache)`)
|
||||
throw new McpConnectionError(
|
||||
'Server recently failed and is in cooldown — try again shortly.',
|
||||
serverId
|
||||
)
|
||||
throw new McpServerCooldownError(serverId)
|
||||
}
|
||||
|
||||
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
||||
|
||||
@@ -133,6 +133,24 @@ export class McpConnectionError extends McpError {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when discovery is refused because the server is inside the
|
||||
* negative-cache cooldown that follows a recent failure. No connection was
|
||||
* attempted, so the condition clears on its own.
|
||||
*
|
||||
* It is a distinct class rather than an `McpConnectionError` whose message
|
||||
* happens to contain "cooldown" because `McpConnectionError` interpolates the
|
||||
* server's display name into that message: a server a caller named after the
|
||||
* word matched the substring test and borrowed this case's wording, telling them
|
||||
* to wait out a cooldown that was never entered.
|
||||
*/
|
||||
export class McpServerCooldownError extends McpConnectionError {
|
||||
constructor(serverName: string) {
|
||||
super('Server recently failed and is in cooldown — try again shortly.', serverName)
|
||||
this.name = 'McpServerCooldownError'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when an OAuth-protected MCP server is reachable but the current
|
||||
* user has not yet authorized Sim. This is a benign "pending" state, not a
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { DEFAULT_EXECUTION_TIMEOUT_MS } from '@/lib/core/execution-limits'
|
||||
import { McpConnectionError, McpOauthAuthorizationRequiredError } from '@/lib/mcp/types'
|
||||
import {
|
||||
McpConnectionError,
|
||||
McpOauthAuthorizationRequiredError,
|
||||
McpServerCooldownError,
|
||||
} from '@/lib/mcp/types'
|
||||
import {
|
||||
categorizeError,
|
||||
createMcpToolId,
|
||||
@@ -319,12 +323,24 @@ describe('categorizeError', () => {
|
||||
expect(result.status).toBe(401)
|
||||
})
|
||||
|
||||
it.concurrent('returns 503 for McpConnectionError with cooldown message', () => {
|
||||
const error = new McpConnectionError('Server in cooldown — try again shortly.', 'mcp-a')
|
||||
it.concurrent('returns 503 for the typed discovery-cooldown refusal', () => {
|
||||
const error = new McpServerCooldownError('mcp-a')
|
||||
const result = categorizeError(error)
|
||||
expect(result.status).toBe(503)
|
||||
})
|
||||
|
||||
/**
|
||||
* The cooldown branch used to be selected by searching the message for
|
||||
* `cooldown`, and `McpConnectionError` interpolates the server's display name
|
||||
* into that message — so a server named after the word was reported as a
|
||||
* transient 503 when its connection had genuinely failed.
|
||||
*/
|
||||
it.concurrent('does not read a cooldown out of a server display name', () => {
|
||||
const error = new McpConnectionError('connect ECONNREFUSED', 'Cooldown Docs')
|
||||
const result = categorizeError(error)
|
||||
expect(result.status).toBe(502)
|
||||
})
|
||||
|
||||
it.concurrent('returns 502 for other McpConnectionError', () => {
|
||||
const error = new McpConnectionError('connect ECONNREFUSED', 'mcp-a')
|
||||
const result = categorizeError(error)
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type McpApiResponse,
|
||||
McpConnectionError,
|
||||
McpOauthAuthorizationRequiredError,
|
||||
McpServerCooldownError,
|
||||
} from '@/lib/mcp/types'
|
||||
import { isMcpTool, MCP } from '@/executor/constants'
|
||||
|
||||
@@ -167,10 +168,10 @@ export function categorizeError(error: unknown): { message: string; status: numb
|
||||
if (error instanceof McpOauthAuthorizationRequiredError || error instanceof UnauthorizedError) {
|
||||
return { message: 'Authentication required', status: 401 }
|
||||
}
|
||||
if (error instanceof McpServerCooldownError) {
|
||||
return { message: 'Server temporarily unavailable', status: 503 }
|
||||
}
|
||||
if (error instanceof McpConnectionError) {
|
||||
if (error.message.toLowerCase().includes('cooldown')) {
|
||||
return { message: 'Server temporarily unavailable', status: 503 }
|
||||
}
|
||||
return { message: 'Connection failed', status: 502 }
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user