Skip to content

Commit bbef414

Browse files
authored
fix(workflow-code): let Mothership apply every tool form the SDK prints (#10732)
Source apply runs the tool-binding authoring check only for a Copilot principal, so no benchmark or user-run test saw it refuse source the SDK prints. A corpus test now prints every tool the editor's picker writes, adds it to the workflow as source, and gates it as Copilot and as a user; Copilot must get nothing a user does not. It found three more refusals beside #10722's: a block tool's title and tool id (the block name and the tool its operation selects), an inline custom tool's custom-<name> id, and the server name and URL the picker records on a Sim Chat MCP tool. Authoring now derives the first two from the binding's definition, as it does for child workflow and MCP tools, and Sim Chat MCP params accept the recorded server name and URL.
1 parent d6661d5 commit bbef414

3 files changed

Lines changed: 218 additions & 12 deletions

File tree

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
/**
2+
* Source apply holds a Copilot principal to checks no other caller meets (`isCopilot` in
3+
* `gateSourceDiff`), so a benchmark or test that applies as a user never sees them refuse. Here
4+
* every tool the editor's picker writes (the corpus `agent-tools` cases) is printed as source and
5+
* written into the same workflow without its tools, as Mothership adds a tool, then gated as
6+
* Copilot and as a user. A finding only Copilot gets is source the SDK itself prints that
7+
* Mothership cannot apply.
8+
*/
9+
import { billingSubscriptionMock } from '@sim/testing/mocks/billing-subscription.mock'
10+
import { integrationsAvailabilityMock } from '@sim/testing/mocks/integrations-availability.mock'
11+
import { describe, expect, it, vi } from 'vitest'
12+
13+
vi.unmock('@/blocks/registry')
14+
vi.unmock('@/tools/metadata-outputs')
15+
vi.unmock('@/tools/registry')
16+
vi.mock('@/lib/integrations/availability.server', () => integrationsAvailabilityMock)
17+
vi.mock('@/lib/billing/core/subscription', () => billingSubscriptionMock)
18+
19+
import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits'
20+
import { gateSourceDiff } from '@/lib/workflows/code/apply/gates'
21+
import { diffGraphs, type SourceGraph } from '@/lib/workflows/code/apply/graph-diff'
22+
import { registryCatalog as catalog } from '@/lib/workflows/code/catalog/registry-catalog.test-helpers'
23+
import { toolInputIds } from '@/lib/workflows/code/catalog/workspace'
24+
import { generateRegistryCorpus } from '@/lib/workflows/code/corpus'
25+
import { applySource, getSource } from '@/lib/workflows/code/corpus/source-harness.test-helpers'
26+
import { validateToolBindingAuthoring } from '@/lib/workflows/tool-input/authoring'
27+
import { getBlock } from '@/blocks/registry'
28+
import type { WorkflowState } from '@/stores/workflows/workflow/types'
29+
import { getToolIdForOperation } from '@/tools/params'
30+
31+
interface ToolAddition {
32+
printed: string
33+
base: SourceGraph
34+
target: SourceGraph
35+
}
36+
37+
/** `state` with every tool-input field emptied: the workflow before its tools were added. */
38+
function withoutTools(state: WorkflowState): WorkflowState {
39+
const stripped = structuredClone(state)
40+
for (const block of Object.values(stripped.blocks)) {
41+
for (const field of toolInputIds(block.type)) {
42+
const subBlock = block.subBlocks?.[field]
43+
if (subBlock) subBlock.value = []
44+
}
45+
}
46+
return stripped
47+
}
48+
49+
/** The printed source of `state`, applied over the same workflow without its tools. */
50+
function addPrintedTools(state: WorkflowState): ToolAddition {
51+
const before = withoutTools(state)
52+
const { files } = getSource(state, catalog)
53+
const applied = applySource(before, getSource(before, catalog), files, catalog)
54+
if (!applied.materialized) {
55+
const errors = applied.compiled.diagnostics.filter((d) => d.severity === 'error')
56+
throw new Error(errors.map((d) => `${d.code}: ${d.message}`).join('; '))
57+
}
58+
const { blocks, edges } = applied.materialized.state
59+
return {
60+
printed: files[SOURCE_ENTRY_FILE],
61+
base: { blocks: before.blocks, edges: before.edges },
62+
target: { blocks, edges },
63+
}
64+
}
65+
66+
function gate({ base, target }: ToolAddition, isCopilot: boolean) {
67+
return gateSourceDiff({
68+
base,
69+
target,
70+
diff: diffGraphs(base, target),
71+
catalog,
72+
keyOf: () => undefined,
73+
permissionConfig: null,
74+
subjectUserId: 'corpus-user',
75+
workspaceId: 'corpus-workspace',
76+
isCopilot,
77+
})
78+
}
79+
80+
// No block types: the agent-tools cases come from the registry itself, not the per-type families.
81+
const additions = generateRegistryCorpus({ blocks: [] })
82+
.filter((corpusCase) => corpusCase.kind === 'agent-tools')
83+
.map((corpusCase) => [corpusCase.id, addPrintedTools(corpusCase.state)] as const)
84+
85+
describe('tools the picker writes, printed and added as Copilot', () => {
86+
it('prints every tool form the SDK has', () => {
87+
const printed = additions.map(([, addition]) => addition.printed).join('\n')
88+
for (const form of ['.tool.', "customTool('", 'mcp(', 'childWorkflow(', 'raw({']) {
89+
expect(printed).toContain(form)
90+
}
91+
expect(new Set(additions.map(([id]) => id.split(':')[1]))).toEqual(
92+
new Set(['agent', 'mothership'])
93+
)
94+
})
95+
96+
it.each(additions)('%s: Copilot is refused nothing a user is not', async (_, addition) => {
97+
const [asCopilot, asUser] = await Promise.all([gate(addition, true), gate(addition, false)])
98+
const copilotOnly = asCopilot.filter(
99+
(finding) => !asUser.some((userFinding) => userFinding.message === finding.message)
100+
)
101+
expect(copilotOnly).toEqual([])
102+
})
103+
})
104+
105+
const slack = getBlock('slack_v2')
106+
const slackSend = getToolIdForOperation('slack_v2', 'send', slack)
107+
const blockTool = { type: 'slack_v2', operation: 'send', params: { channel: 'support' } }
108+
const inlineTool = {
109+
type: 'custom-tool',
110+
title: 'lookup',
111+
code: 'return 1',
112+
schema: { function: { name: 'lookup', parameters: { type: 'object' } } },
113+
}
114+
115+
describe('a label only the binding derives', () => {
116+
it.each([
117+
[
118+
'a block tool with its picker labels',
119+
{ ...blockTool, title: slack?.name, toolId: slackSend },
120+
undefined,
121+
],
122+
[
123+
"a block tool naming another operation's tool",
124+
{ ...blockTool, toolId: slack?.tools.access.find((toolId) => toolId !== slackSend) },
125+
'read-only',
126+
],
127+
[
128+
'an inline custom tool with its picker id',
129+
{ ...inlineTool, toolId: 'custom-lookup' },
130+
undefined,
131+
],
132+
[
133+
'an inline custom tool with another id',
134+
{ ...inlineTool, toolId: 'custom-other' },
135+
'read-only',
136+
],
137+
])('%s is judged by Copilot authoring', (_, tool, refusal) => {
138+
const error = validateToolBindingAuthoring('agent', [tool])
139+
if (refusal) expect(error).toContain(refusal)
140+
else expect(error).toBeUndefined()
141+
})
142+
})

‎apps/sim/lib/workflows/code/corpus/generate.ts‎

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
import { isTriggerTarget } from '@sim/workflow-code/catalog/view'
2828
import { normalizeWorkflowBlockName } from '@sim/workflow-types/workflow'
29+
import { MCP_SERVER_ADVANCED_TOOL_TYPE } from '@/lib/mcp/shared'
2930
import {
3031
type BlockFixture,
3132
buildBlockFixture,
@@ -45,6 +46,7 @@ import { hasTriggerCapability } from '@/lib/workflows/triggers/utils'
4546
import { getBlockRegistry } from '@/blocks/registry'
4647
import type { BlockConfig } from '@/blocks/types'
4748
import type { BlockState, Loop, Parallel, WorkflowState } from '@/stores/workflows/workflow/types'
49+
import { getToolIdForOperation } from '@/tools/params'
4850

4951
type CorpusCaseKind =
5052
| 'operation'
@@ -892,17 +894,23 @@ function crlfCases(registry: Registry, seed: number): CorpusCase[] {
892894

893895
/**
894896
* Agent tool entries the editor's tool picker writes (tool-input.tsx): an MCP server tool with its
895-
* input schema snapshot, a deployed workflow as a tool (`workflow_input`), a block operation as a
896-
* tool (Slack send to a picked channel), one whose params repeat its operation, and a workspace
897-
* custom tool by id.
897+
* input schema snapshot, a whole MCP server with an operation policy, a deployed workflow as a tool
898+
* (`workflow_input`), a block operation as a tool (Slack send to a picked channel), one whose
899+
* params repeat its operation, a workspace custom tool by id, and an inline custom tool. A Sim Chat
900+
* block takes the MCP bindings.
898901
*/
899902
function agentToolCases(registry: Registry, seed: number): CorpusCase[] {
900903
const agent = registry.byType.get('agent')
901904
if (!agent) return []
902-
const toolCase = (detail: string, makeTools: (b: CaseBuilder) => unknown[]) => {
903-
const builder = new CaseBuilder(seed, `agent-tools:agent:${detail}`)
905+
const mothership = registry.byType.get('mothership')
906+
const toolCase = (
907+
detail: string,
908+
makeTools: (b: CaseBuilder) => unknown[],
909+
host: BlockConfig = agent
910+
) => {
911+
const builder = new CaseBuilder(seed, `agent-tools:${host.type}:${detail}`)
904912
const start = startBlock(builder, registry)
905-
const { block } = subject(builder, registry, agent, { name: 'Agent' })
913+
const { block } = subject(builder, registry, host, { name: host.name })
906914
const tools = block.subBlocks.tools
907915
if (tools) tools.value = makeTools(builder) as typeof tools.value
908916
builder.connect(start, block.id)
@@ -940,9 +948,17 @@ function agentToolCases(registry: Registry, seed: number): CorpusCase[] {
940948
isExpanded: false,
941949
usageControl: 'auto',
942950
})
951+
const mcpServerTool = (serverId: string) => ({
952+
type: MCP_SERVER_ADVANCED_TOOL_TYPE,
953+
operationPolicy: { mode: 'allow', operations: [] },
954+
params: { serverId },
955+
isExpanded: false,
956+
usageControl: 'auto',
957+
})
943958
const builderTool = () => ({
944959
type: 'slack_v2',
945960
title: 'Slack',
961+
toolId: getToolIdForOperation('slack_v2', 'send', registry.byType.get('slack_v2')),
946962
operation: 'send',
947963
params: { channel: 'corpus-pick-1', text: CORPUS_TEXT },
948964
isExpanded: false,
@@ -969,18 +985,51 @@ function agentToolCases(registry: Registry, seed: number): CorpusCase[] {
969985
customToolId: 'corpus-custom-tool',
970986
usageControl: 'auto',
971987
})
988+
const inlineCustomTool = () => ({
989+
type: 'custom-tool',
990+
title: 'lookup_order',
991+
toolId: 'custom-lookup_order',
992+
params: {},
993+
isExpanded: false,
994+
schema: {
995+
type: 'function',
996+
function: {
997+
name: 'lookup_order',
998+
description: 'Look up an order',
999+
parameters: {
1000+
type: 'object',
1001+
properties: { orderId: { type: 'string', description: 'The order id' } },
1002+
required: ['orderId'],
1003+
},
1004+
},
1005+
},
1006+
code: 'return { orderId }',
1007+
usageControl: 'auto',
1008+
})
9721009
return [
9731010
toolCase('mcp', (b) => [mcpTool(b)]),
9741011
toolCase('workflow-input', (b) => [workflowTool(b)]),
9751012
toolCase('mcp-and-workflow-input', (b) => [mcpTool(b), workflowTool(b)]),
9761013
toolCase('builder-and-custom', () => [builderTool(), customTool()]),
9771014
toolCase('params-repeat-operation', () => [operationInParamsTool()]),
1015+
toolCase('custom', () => [customTool()]),
1016+
toolCase('inline-custom', () => [inlineCustomTool()]),
1017+
toolCase('mcp-server', (b) => [mcpServerTool(b.newId())]),
9781018
toolCase('every-kind', (b) => [
9791019
builderTool(),
9801020
customTool(),
9811021
mcpTool(b, 'corpus-mcp-server'),
9821022
workflowTool(b, 'corpus-workflow'),
9831023
]),
1024+
...(mothership
1025+
? [
1026+
toolCase(
1027+
'mcp-and-server',
1028+
(b) => [mcpTool(b, 'corpus-mcp-server'), mcpServerTool('corpus-mcp-server-all')],
1029+
mothership
1030+
),
1031+
]
1032+
: []),
9841033
]
9851034
}
9861035

‎apps/sim/lib/workflows/tool-input/authoring.ts‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ import {
99
v2AgentMcpToolSchema,
1010
} from '@/lib/api/contracts/v2/workflows'
1111
import { createMcpToolId } from '@/lib/mcp/shared'
12+
import { getBlock } from '@/blocks/registry'
13+
import { getToolIdForOperation } from '@/tools/params'
1214

1315
/** Attachment identity comes from its definition, never an author-supplied alias. */
1416
const identityFields = ['title', 'name', 'toolId', 'functionName'] as const
@@ -44,9 +46,10 @@ const mothershipTools = z
4446
mcp.extend({
4547
params: v2AgentMcpToolSchema.shape.params.def.left
4648
.pick({ serverId: true, toolName: true })
49+
.extend({ serverName: z.string().optional(), serverUrl: z.string().optional() })
4750
.strict()
4851
.describe(
49-
'MCP identity only. Sim Chat discovers arguments at call time; fixed arguments are not supported.'
52+
'MCP identity, plus the server name and URL the tool picker records. Sim Chat discovers arguments at call time; fixed arguments are not supported.'
5053
),
5154
}),
5255
mcpServer,
@@ -65,17 +68,29 @@ type IdentityField = (typeof identityFields)[number]
6568

6669
/**
6770
* The labels the editor's tool picker derives from a binding's own definition (tool-input.tsx): a
68-
* child workflow tool's fixed title and tool id, and an MCP tool's name and the id built from it.
69-
* They name nothing the binding does not, so writing them is not an override.
71+
* child workflow tool's fixed title and tool id, an MCP tool's name and the id built from it, an
72+
* inline custom tool's id built from its function name, and a block tool's block name and the tool
73+
* its operation selects. They name nothing the binding does not, so writing them is not an
74+
* override.
7075
*/
7176
function definitionLabels(tool: Record<string, unknown>): Partial<Record<IdentityField, string>> {
7277
if (tool.type === 'workflow_input') return { title: 'Workflow', toolId: 'workflow_executor' }
7378
const params = isPlainRecord(tool.params) ? tool.params : {}
7479
const { serverId, toolName } = params
75-
if (tool.type === 'mcp' && typeof serverId === 'string' && typeof toolName === 'string') {
76-
return { title: toolName, toolId: createMcpToolId(serverId, toolName) }
80+
if (tool.type === 'mcp') {
81+
return typeof serverId === 'string' && typeof toolName === 'string'
82+
? { title: toolName, toolId: createMcpToolId(serverId, toolName) }
83+
: {}
7784
}
78-
return {}
85+
if (tool.type === 'custom-tool') {
86+
const fn = isPlainRecord(tool.schema) ? tool.schema.function : undefined
87+
const name = isPlainRecord(fn) ? fn.name : undefined
88+
return { toolId: `custom-${typeof name === 'string' && name ? name : 'unknown'}` }
89+
}
90+
const block = typeof tool.type === 'string' ? getBlock(tool.type) : undefined
91+
if (!block) return {}
92+
const operation = typeof tool.operation === 'string' ? tool.operation : undefined
93+
return { title: block.name, toolId: getToolIdForOperation(block.type, operation, block) }
7994
}
8095

8196
function bindingIdentity(tool: Record<string, unknown>): unknown[] {

0 commit comments

Comments
 (0)