Skip to content

Commit 8b0c47b

Browse files
authored
chore(executor): extract shared utils and remove dead code from handlers (#3334)
1 parent 774771f commit 8b0c47b

File tree

9 files changed

+251
-464
lines changed

9 files changed

+251
-464
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,7 @@ start-collector.sh
7373
## Helm Chart Tests
7474
helm/sim/test
7575
i18n.cache
76+
77+
## Claude Code
78+
.claude/launch.json
79+
.claude/worktrees/

apps/sim/executor/handlers/agent/agent-handler.ts

Lines changed: 35 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import { db } from '@sim/db'
2-
import { account, mcpServers } from '@sim/db/schema'
2+
import { mcpServers } from '@sim/db/schema'
33
import { createLogger } from '@sim/logger'
44
import { and, eq, inArray, isNull } from 'drizzle-orm'
55
import { createMcpToolId } from '@/lib/mcp/utils'
6-
import { refreshTokenIfNeeded, resolveOAuthAccountId } from '@/app/api/auth/oauth/utils'
76
import { getAllBlocks } from '@/blocks'
87
import type { BlockOutput } from '@/blocks/types'
98
import {
@@ -30,6 +29,7 @@ import type { BlockHandler, ExecutionContext, StreamingExecution } from '@/execu
3029
import { collectBlockData } from '@/executor/utils/block-data'
3130
import { buildAPIUrl, buildAuthHeaders } from '@/executor/utils/http'
3231
import { stringifyJSON } from '@/executor/utils/json'
32+
import { resolveVertexCredential } from '@/executor/utils/vertex-credential'
3333
import { executeProviderRequest } from '@/providers'
3434
import { getProviderFromModel, transformBlockTool } from '@/providers/utils'
3535
import type { SerializedBlock } from '@/serializer/types'
@@ -439,24 +439,15 @@ export class AgentBlockHandler implements BlockHandler {
439439
tool: ToolInput
440440
): Promise<any> {
441441
const { serverId, toolName, serverName, ...userProvidedParams } = tool.params || {}
442-
443-
const { filterSchemaForLLM } = await import('@/tools/params')
444-
const filteredSchema = filterSchemaForLLM(
445-
tool.schema || { type: 'object', properties: {} },
446-
userProvidedParams
447-
)
448-
449-
const toolId = createMcpToolId(serverId, toolName)
450-
451-
return {
452-
id: toolId,
453-
name: toolName,
442+
return this.buildMcpTool({
443+
serverId,
444+
toolName,
454445
description:
455446
tool.schema?.description || `MCP tool ${toolName} from ${serverName || serverId}`,
456-
parameters: filteredSchema,
457-
params: userProvidedParams,
458-
usageControl: tool.usageControl || 'auto',
459-
}
447+
schema: tool.schema || { type: 'object', properties: {} },
448+
userProvidedParams,
449+
usageControl: tool.usageControl,
450+
})
460451
}
461452

462453
/**
@@ -585,22 +576,35 @@ export class AgentBlockHandler implements BlockHandler {
585576
serverId: string
586577
): Promise<any> {
587578
const { toolName, ...userProvidedParams } = tool.params || {}
579+
return this.buildMcpTool({
580+
serverId,
581+
toolName,
582+
description: mcpTool.description || `MCP tool ${toolName} from ${mcpTool.serverName}`,
583+
schema: mcpTool.inputSchema || { type: 'object', properties: {} },
584+
userProvidedParams,
585+
usageControl: tool.usageControl,
586+
})
587+
}
588588

589+
private async buildMcpTool(config: {
590+
serverId: string
591+
toolName: string
592+
description: string
593+
schema: any
594+
userProvidedParams: Record<string, any>
595+
usageControl?: string
596+
}): Promise<any> {
589597
const { filterSchemaForLLM } = await import('@/tools/params')
590-
const filteredSchema = filterSchemaForLLM(
591-
mcpTool.inputSchema || { type: 'object', properties: {} },
592-
userProvidedParams
593-
)
594-
595-
const toolId = createMcpToolId(serverId, toolName)
598+
const filteredSchema = filterSchemaForLLM(config.schema, config.userProvidedParams)
599+
const toolId = createMcpToolId(config.serverId, config.toolName)
596600

597601
return {
598602
id: toolId,
599-
name: toolName,
600-
description: mcpTool.description || `MCP tool ${toolName} from ${mcpTool.serverName}`,
603+
name: config.toolName,
604+
description: config.description,
601605
parameters: filteredSchema,
602-
params: userProvidedParams,
603-
usageControl: tool.usageControl || 'auto',
606+
params: config.userProvidedParams,
607+
usageControl: config.usageControl || 'auto',
604608
}
605609
}
606610

@@ -924,9 +928,9 @@ export class AgentBlockHandler implements BlockHandler {
924928
let finalApiKey: string | undefined = providerRequest.apiKey
925929

926930
if (providerId === 'vertex' && providerRequest.vertexCredential) {
927-
finalApiKey = await this.resolveVertexCredential(
931+
finalApiKey = await resolveVertexCredential(
928932
providerRequest.vertexCredential,
929-
ctx.workflowId
933+
'vertex-agent'
930934
)
931935
}
932936

@@ -973,37 +977,6 @@ export class AgentBlockHandler implements BlockHandler {
973977
}
974978
}
975979

976-
/**
977-
* Resolves a Vertex AI OAuth credential to an access token
978-
*/
979-
private async resolveVertexCredential(credentialId: string, workflowId: string): Promise<string> {
980-
const requestId = `vertex-${Date.now()}`
981-
982-
logger.info(`[${requestId}] Resolving Vertex AI credential: ${credentialId}`)
983-
984-
const resolved = await resolveOAuthAccountId(credentialId)
985-
if (!resolved) {
986-
throw new Error(`Vertex AI credential is not a valid OAuth credential: ${credentialId}`)
987-
}
988-
989-
const credential = await db.query.account.findFirst({
990-
where: eq(account.id, resolved.accountId),
991-
})
992-
993-
if (!credential) {
994-
throw new Error(`Vertex AI credential not found: ${credentialId}`)
995-
}
996-
997-
const { accessToken } = await refreshTokenIfNeeded(requestId, credential, resolved.accountId)
998-
999-
if (!accessToken) {
1000-
throw new Error('Failed to get Vertex AI access token')
1001-
}
1002-
1003-
logger.info(`[${requestId}] Successfully resolved Vertex AI credential`)
1004-
return accessToken
1005-
}
1006-
1007980
private handleExecutionError(
1008981
error: any,
1009982
startTime: number,
@@ -1187,7 +1160,7 @@ export class AgentBlockHandler implements BlockHandler {
11871160
},
11881161
toolCalls: {
11891162
list: result.toolCalls?.map(this.formatToolCall.bind(this)) || [],
1190-
count: result.toolCalls?.length || DEFAULTS.EXECUTION_TIME,
1163+
count: result.toolCalls?.length ?? 0,
11911164
},
11921165
providerTiming: result.timing,
11931166
cost: result.cost,

apps/sim/executor/handlers/evaluator/evaluator-handler.ts

Lines changed: 7 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
1-
import { db } from '@sim/db'
2-
import { account } from '@sim/db/schema'
31
import { createLogger } from '@sim/logger'
4-
import { eq } from 'drizzle-orm'
5-
import { refreshTokenIfNeeded, resolveOAuthAccountId } from '@/app/api/auth/oauth/utils'
62
import type { BlockOutput } from '@/blocks/types'
73
import { validateModelProvider } from '@/ee/access-control/utils/permission-check'
84
import { BlockType, DEFAULTS, EVALUATOR } from '@/executor/constants'
95
import type { BlockHandler, ExecutionContext } from '@/executor/types'
106
import { buildAPIUrl, buildAuthHeaders, extractAPIErrorMessage } from '@/executor/utils/http'
117
import { isJSONString, parseJSON, stringifyJSON } from '@/executor/utils/json'
8+
import { resolveVertexCredential } from '@/executor/utils/vertex-credential'
129
import { calculateCost, getProviderFromModel } from '@/providers/utils'
1310
import type { SerializedBlock } from '@/serializer/types'
1411

@@ -44,7 +41,10 @@ export class EvaluatorBlockHandler implements BlockHandler {
4441

4542
let finalApiKey: string | undefined = evaluatorConfig.apiKey
4643
if (providerId === 'vertex' && evaluatorConfig.vertexCredential) {
47-
finalApiKey = await this.resolveVertexCredential(evaluatorConfig.vertexCredential)
44+
finalApiKey = await resolveVertexCredential(
45+
evaluatorConfig.vertexCredential,
46+
'vertex-evaluator'
47+
)
4848
}
4949

5050
const processedContent = this.processContent(inputs.content)
@@ -234,7 +234,7 @@ export class EvaluatorBlockHandler implements BlockHandler {
234234
if (Object.keys(parsedContent).length === 0) {
235235
validMetrics.forEach((metric: any) => {
236236
if (metric?.name) {
237-
metricScores[metric.name.toLowerCase()] = DEFAULTS.EXECUTION_TIME
237+
metricScores[metric.name.toLowerCase()] = 0
238238
}
239239
})
240240
return metricScores
@@ -273,37 +273,6 @@ export class EvaluatorBlockHandler implements BlockHandler {
273273
}
274274

275275
logger.warn(`Metric "${metricName}" not found in LLM response`)
276-
return DEFAULTS.EXECUTION_TIME
277-
}
278-
279-
/**
280-
* Resolves a Vertex AI OAuth credential to an access token
281-
*/
282-
private async resolveVertexCredential(credentialId: string): Promise<string> {
283-
const requestId = `vertex-evaluator-${Date.now()}`
284-
285-
logger.info(`[${requestId}] Resolving Vertex AI credential: ${credentialId}`)
286-
287-
const resolved = await resolveOAuthAccountId(credentialId)
288-
if (!resolved) {
289-
throw new Error(`Vertex AI credential is not a valid OAuth credential: ${credentialId}`)
290-
}
291-
292-
const credential = await db.query.account.findFirst({
293-
where: eq(account.id, resolved.accountId),
294-
})
295-
296-
if (!credential) {
297-
throw new Error(`Vertex AI credential not found: ${credentialId}`)
298-
}
299-
300-
const { accessToken } = await refreshTokenIfNeeded(requestId, credential, resolved.accountId)
301-
302-
if (!accessToken) {
303-
throw new Error('Failed to get Vertex AI access token')
304-
}
305-
306-
logger.info(`[${requestId}] Successfully resolved Vertex AI credential`)
307-
return accessToken
276+
return 0
308277
}
309278
}

0 commit comments

Comments
 (0)