mirror of
https://github.com/n8n-io/n8n.git
synced 2026-12-04 00:30:34 +00:00
feat(core, editor): Add tool call log for custom MCP (no-changelog) (#46265)
Co-authored-by: n8n-cat-bot[bot] <283985454+n8n-cat-bot[bot]@users.noreply.github.com> Co-authored-by: Roman Makowiak <roman.makowiak@n8n.io> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
47 files changed
+4364
-62
No files matched your search
Generated
+21
@@ -132,6 +132,7 @@ Auto-generated from the PostgreSQL migrations in @n8n/db. Do not edit by hand.
|
||||
| [public.mcp_server_connection](public.mcp_server_connection.md) | 6 | | BASE TABLE |
|
||||
| [public.mcp_server_reserved_slug](public.mcp_server_reserved_slug.md) | 3 | | BASE TABLE |
|
||||
| [public.mcp_server_tool](public.mcp_server_tool.md) | 11 | | BASE TABLE |
|
||||
| [public.mcp_server_tool_call](public.mcp_server_tool_call.md) | 14 | | BASE TABLE |
|
||||
| [public.migration_finding](public.migration_finding.md) | 10 | | BASE TABLE |
|
||||
| [public.migration_finding_sync](public.migration_finding_sync.md) | 3 | | BASE TABLE |
|
||||
| [public.migration_workflow_owner](public.migration_workflow_owner.md) | 7 | | BASE TABLE |
|
||||
@@ -429,6 +430,10 @@ erDiagram
|
||||
"public.mcp_server_connection" }o--|| "public.mcp_server" : "FOREIGN KEY (#quot;serverId#quot;) REFERENCES mcp_server(id) ON DELETE CASCADE"
|
||||
"public.mcp_server_reserved_slug" }o--|| "public.mcp_server" : "FOREIGN KEY (#quot;serverId#quot;) REFERENCES mcp_server(id) ON DELETE CASCADE"
|
||||
"public.mcp_server_tool" }o--|| "public.mcp_server" : "FOREIGN KEY (#quot;serverId#quot;) REFERENCES mcp_server(id) ON DELETE CASCADE"
|
||||
"public.mcp_server_tool_call" }o--o| "public.user" : "FOREIGN KEY (#quot;userId#quot;) REFERENCES #quot;user#quot;(id) ON DELETE SET NULL"
|
||||
"public.mcp_server_tool_call" }o--o| "public.oauth_clients" : "FOREIGN KEY (#quot;oauthClientId#quot;) REFERENCES oauth_clients(id) ON DELETE SET NULL"
|
||||
"public.mcp_server_tool_call" }o--|| "public.mcp_server" : "FOREIGN KEY (#quot;serverId#quot;) REFERENCES mcp_server(id) ON DELETE CASCADE"
|
||||
"public.mcp_server_tool_call" }o--o| "public.mcp_server_tool" : "FOREIGN KEY (#quot;toolId#quot;) REFERENCES mcp_server_tool(id) ON DELETE SET NULL"
|
||||
"public.migration_finding" }o--|| "public.workflow_entity" : "FOREIGN KEY (#quot;workflowId#quot;) REFERENCES workflow_entity(id) ON DELETE CASCADE"
|
||||
"public.migration_workflow_owner" }o--o| "public.user" : "FOREIGN KEY (#quot;userId#quot;) REFERENCES #quot;user#quot;(id) ON DELETE SET NULL"
|
||||
"public.migration_workflow_owner" }o--o| "public.user" : "FOREIGN KEY (#quot;assignedById#quot;) REFERENCES #quot;user#quot;(id) ON DELETE SET NULL"
|
||||
@@ -1845,6 +1850,22 @@ erDiagram
|
||||
varchar_64_ toolName
|
||||
timestamp_3__with_time_zone updatedAt
|
||||
}
|
||||
"public.mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
integer durationMs
|
||||
text errorMessage
|
||||
varchar_36_ executionId
|
||||
integer id
|
||||
varchar oauthClientId FK
|
||||
uuid serverId FK
|
||||
timestamp_3__with_time_zone startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
uuid toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
uuid userId FK
|
||||
}
|
||||
"public.migration_finding" {
|
||||
timestamp_3__with_time_zone createdAt
|
||||
integer id
|
||||
|
||||
+18
-1
@@ -8,7 +8,7 @@
|
||||
| createdById | uuid | | true | | [public.user](public.user.md) | Creator. NULL after the user is deleted |
|
||||
| deletedAt | timestamp(3) with time zone | | true | | | Soft delete. NULL for a server that is not deleted |
|
||||
| description | text | ''::text | false | | | Clients get it as the MCP instructions |
|
||||
| id | uuid | | false | [public.mcp_server_block](public.mcp_server_block.md) [public.mcp_server_connection](public.mcp_server_connection.md) [public.mcp_server_reserved_slug](public.mcp_server_reserved_slug.md) [public.mcp_server_tool](public.mcp_server_tool.md) | | UUIDv7, made by the application |
|
||||
| id | uuid | | false | [public.mcp_server_block](public.mcp_server_block.md) [public.mcp_server_connection](public.mcp_server_connection.md) [public.mcp_server_reserved_slug](public.mcp_server_reserved_slug.md) [public.mcp_server_tool](public.mcp_server_tool.md) [public.mcp_server_tool_call](public.mcp_server_tool_call.md) | | UUIDv7, made by the application |
|
||||
| name | varchar(128) | | false | | | |
|
||||
| projectId | varchar(36) | | false | | [public.project](public.project.md) | |
|
||||
| slug | varchar(128) | | false | | | Path segment of the server URL. It never changes. A deleted server keeps it, until its project is deleted |
|
||||
@@ -48,6 +48,7 @@ erDiagram
|
||||
"public.mcp_server_connection" }o--|| "public.mcp_server" : "FOREIGN KEY (#quot;serverId#quot;) REFERENCES mcp_server(id) ON DELETE CASCADE"
|
||||
"public.mcp_server_reserved_slug" }o--|| "public.mcp_server" : "FOREIGN KEY (#quot;serverId#quot;) REFERENCES mcp_server(id) ON DELETE CASCADE"
|
||||
"public.mcp_server_tool" }o--|| "public.mcp_server" : "FOREIGN KEY (#quot;serverId#quot;) REFERENCES mcp_server(id) ON DELETE CASCADE"
|
||||
"public.mcp_server_tool_call" }o--|| "public.mcp_server" : "FOREIGN KEY (#quot;serverId#quot;) REFERENCES mcp_server(id) ON DELETE CASCADE"
|
||||
"public.mcp_server" }o--|| "public.project" : "FOREIGN KEY (#quot;projectId#quot;) REFERENCES project(id) ON DELETE CASCADE"
|
||||
|
||||
"public.mcp_server" {
|
||||
@@ -111,6 +112,22 @@ erDiagram
|
||||
varchar_64_ toolName
|
||||
timestamp_3__with_time_zone updatedAt
|
||||
}
|
||||
"public.mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
integer durationMs
|
||||
text errorMessage
|
||||
varchar_36_ executionId
|
||||
integer id
|
||||
varchar oauthClientId FK
|
||||
uuid serverId FK
|
||||
timestamp_3__with_time_zone startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
uuid toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
uuid userId FK
|
||||
}
|
||||
"public.project" {
|
||||
timestamp_3__with_time_zone createdAt
|
||||
uuid creatorId FK
|
||||
|
||||
+18
-1
@@ -7,7 +7,7 @@
|
||||
| createdAt | timestamp(3) with time zone | CURRENT_TIMESTAMP(3) | false | | | |
|
||||
| description | text | ''::text | false | | | |
|
||||
| draftSource | varchar(16) | 'defaults'::character varying | false | | | Who wrote the tool text: an AI draft, the defaults of the target, or the builder |
|
||||
| id | uuid | | false | | | UUIDv7, made by the application |
|
||||
| id | uuid | | false | [public.mcp_server_tool_call](public.mcp_server_tool_call.md) | | UUIDv7, made by the application |
|
||||
| kind | varchar(16) | | false | | | What the tool runs: a workflow, a node, an agent, or a skill |
|
||||
| position | integer | 0 | false | | | Order of the tool in the server |
|
||||
| serverId | uuid | | false | | [public.mcp_server](public.mcp_server.md) | |
|
||||
@@ -46,6 +46,7 @@
|
||||
```mermaid
|
||||
erDiagram
|
||||
|
||||
"public.mcp_server_tool_call" }o--o| "public.mcp_server_tool" : "FOREIGN KEY (#quot;toolId#quot;) REFERENCES mcp_server_tool(id) ON DELETE SET NULL"
|
||||
"public.mcp_server_tool" }o--|| "public.mcp_server" : "FOREIGN KEY (#quot;serverId#quot;) REFERENCES mcp_server(id) ON DELETE CASCADE"
|
||||
|
||||
"public.mcp_server_tool" {
|
||||
@@ -61,6 +62,22 @@ erDiagram
|
||||
varchar_64_ toolName
|
||||
timestamp_3__with_time_zone updatedAt
|
||||
}
|
||||
"public.mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
integer durationMs
|
||||
text errorMessage
|
||||
varchar_36_ executionId
|
||||
integer id
|
||||
varchar oauthClientId FK
|
||||
uuid serverId FK
|
||||
timestamp_3__with_time_zone startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
uuid toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
uuid userId FK
|
||||
}
|
||||
"public.mcp_server" {
|
||||
timestamp_3__with_time_zone createdAt
|
||||
uuid createdById FK
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
# public.mcp_server_tool_call
|
||||
|
||||
## Columns
|
||||
|
||||
| Name | Type | Default | Nullable | Children | Parents | Comment |
|
||||
| ---- | ---- | ------- | -------- | -------- | ------- | ------- |
|
||||
| clientName | varchar(255) | | false | | | Snapshot of the OAuth client name at call time, e.g. "Claude Code" |
|
||||
| durationMs | integer | | false | | | Duration of the tool call in milliseconds |
|
||||
| errorMessage | text | | true | | | Safe error summary returned for a failed call. NULL on success |
|
||||
| executionId | varchar(36) | | true | | | Workflow execution ID when a workflow run started. NULL otherwise |
|
||||
| id | integer | | false | | | |
|
||||
| oauthClientId | varchar | | true | | [public.oauth_clients](public.oauth_clients.md) | OAuth client that called the tool. NULL when unavailable or deleted |
|
||||
| serverId | uuid | | false | | [public.mcp_server](public.mcp_server.md) | |
|
||||
| startedAt | timestamp(3) with time zone | CURRENT_TIMESTAMP(3) | false | | | When the tool call started |
|
||||
| status | varchar(16) | | false | | | Outcome of the tool call: success, error, or unfinished (the run outlived the call) |
|
||||
| targetId | varchar(36) | | true | | | ID of the target workflow, agent, or skill at call time. NULL for a node tool |
|
||||
| toolId | uuid | | true | | [public.mcp_server_tool](public.mcp_server_tool.md) | Tool row at call time. NULL when the tool was removed |
|
||||
| toolKind | varchar(16) | | false | | | What the tool ran: a workflow, a node, an agent, or a skill |
|
||||
| toolName | varchar(64) | | false | | | Snapshot of the tool name at call time |
|
||||
| userId | uuid | | true | | [public.user](public.user.md) | Person who called the tool. NULL after the user is deleted |
|
||||
|
||||
## Constraints
|
||||
|
||||
| Name | Type | Definition |
|
||||
| ---- | ---- | ---------- |
|
||||
| CHK_mcp_server_tool_call_status | CHECK | CHECK (((status)::text = ANY ((ARRAY['success'::character varying, 'error'::character varying, 'unfinished'::character varying])::text[]))) |
|
||||
| CHK_mcp_server_tool_call_toolKind | CHECK | CHECK ((("toolKind")::text = ANY ((ARRAY['workflow'::character varying, 'node'::character varying, 'agent'::character varying, 'skill'::character varying])::text[]))) |
|
||||
| FK_18ad188e9975d252128e1097007 | FOREIGN KEY | FOREIGN KEY ("toolId") REFERENCES mcp_server_tool(id) ON DELETE SET NULL |
|
||||
| FK_29fac15a0c61fd77fe2c0b5bf44 | FOREIGN KEY | FOREIGN KEY ("oauthClientId") REFERENCES oauth_clients(id) ON DELETE SET NULL |
|
||||
| FK_44f4821858f73c1871d000f8e7a | FOREIGN KEY | FOREIGN KEY ("serverId") REFERENCES mcp_server(id) ON DELETE CASCADE |
|
||||
| FK_6c1ca8e2b27fda7624b2e0888d7 | FOREIGN KEY | FOREIGN KEY ("userId") REFERENCES "user"(id) ON DELETE SET NULL |
|
||||
| PK_b63c0a77d5906cc5e77436584f7 | PRIMARY KEY | PRIMARY KEY (id) |
|
||||
| mcp_server_tool_call_clientName_not_null | n | NOT NULL "clientName" |
|
||||
| mcp_server_tool_call_durationMs_not_null | n | NOT NULL "durationMs" |
|
||||
| mcp_server_tool_call_id_not_null | n | NOT NULL id |
|
||||
| mcp_server_tool_call_serverId_not_null | n | NOT NULL "serverId" |
|
||||
| mcp_server_tool_call_startedAt_not_null | n | NOT NULL "startedAt" |
|
||||
| mcp_server_tool_call_status_not_null | n | NOT NULL status |
|
||||
| mcp_server_tool_call_toolKind_not_null | n | NOT NULL "toolKind" |
|
||||
| mcp_server_tool_call_toolName_not_null | n | NOT NULL "toolName" |
|
||||
|
||||
## Indexes
|
||||
|
||||
| Name | Definition |
|
||||
| ---- | ---------- |
|
||||
| IDX_110df42f5591dbb48d0bbda4ec | CREATE INDEX "IDX_110df42f5591dbb48d0bbda4ec" ON public.mcp_server_tool_call USING btree ("serverId", "startedAt", id) |
|
||||
| IDX_18ad188e9975d252128e109700 | CREATE INDEX "IDX_18ad188e9975d252128e109700" ON public.mcp_server_tool_call USING btree ("toolId") |
|
||||
| IDX_29fac15a0c61fd77fe2c0b5bf4 | CREATE INDEX "IDX_29fac15a0c61fd77fe2c0b5bf4" ON public.mcp_server_tool_call USING btree ("oauthClientId") |
|
||||
| IDX_44155d3ec8733193ec47d233ac | CREATE INDEX "IDX_44155d3ec8733193ec47d233ac" ON public.mcp_server_tool_call USING btree ("serverId", status, id) |
|
||||
| IDX_6c1ca8e2b27fda7624b2e0888d | CREATE INDEX "IDX_6c1ca8e2b27fda7624b2e0888d" ON public.mcp_server_tool_call USING btree ("userId") |
|
||||
| IDX_7f42993460a22186d3c6e6926b | CREATE INDEX "IDX_7f42993460a22186d3c6e6926b" ON public.mcp_server_tool_call USING btree ("serverId", "durationMs", id) |
|
||||
| IDX_8e6ac48653f0e81a3a1c2adb2e | CREATE INDEX "IDX_8e6ac48653f0e81a3a1c2adb2e" ON public.mcp_server_tool_call USING btree ("startedAt") |
|
||||
| IDX_d9f0af248f53a307dda2cb3001 | CREATE INDEX "IDX_d9f0af248f53a307dda2cb3001" ON public.mcp_server_tool_call USING btree ("serverId", "toolName", id) |
|
||||
| PK_b63c0a77d5906cc5e77436584f7 | CREATE UNIQUE INDEX "PK_b63c0a77d5906cc5e77436584f7" ON public.mcp_server_tool_call USING btree (id) |
|
||||
|
||||
## Relations
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
|
||||
"public.mcp_server_tool_call" }o--o| "public.oauth_clients" : "FOREIGN KEY (#quot;oauthClientId#quot;) REFERENCES oauth_clients(id) ON DELETE SET NULL"
|
||||
"public.mcp_server_tool_call" }o--|| "public.mcp_server" : "FOREIGN KEY (#quot;serverId#quot;) REFERENCES mcp_server(id) ON DELETE CASCADE"
|
||||
"public.mcp_server_tool_call" }o--o| "public.mcp_server_tool" : "FOREIGN KEY (#quot;toolId#quot;) REFERENCES mcp_server_tool(id) ON DELETE SET NULL"
|
||||
"public.mcp_server_tool_call" }o--o| "public.user" : "FOREIGN KEY (#quot;userId#quot;) REFERENCES #quot;user#quot;(id) ON DELETE SET NULL"
|
||||
|
||||
"public.mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
integer durationMs
|
||||
text errorMessage
|
||||
varchar_36_ executionId
|
||||
integer id
|
||||
varchar oauthClientId FK
|
||||
uuid serverId FK
|
||||
timestamp_3__with_time_zone startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
uuid toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
uuid userId FK
|
||||
}
|
||||
"public.oauth_clients" {
|
||||
varchar_255_ clientSecret
|
||||
bigint clientSecretExpiresAt
|
||||
timestamp_3__with_time_zone createdAt
|
||||
json grantTypes
|
||||
varchar id
|
||||
boolean isFirstParty
|
||||
varchar_255_ name
|
||||
json redirectUris
|
||||
uuid serviceAccountId FK
|
||||
varchar_255_ tokenEndpointAuthMethod
|
||||
timestamp_3__with_time_zone updatedAt
|
||||
}
|
||||
"public.mcp_server" {
|
||||
timestamp_3__with_time_zone createdAt
|
||||
uuid createdById FK
|
||||
timestamp_3__with_time_zone deletedAt
|
||||
text description
|
||||
uuid id
|
||||
varchar_128_ name
|
||||
varchar_36_ projectId FK
|
||||
varchar_128_ slug
|
||||
timestamp_3__with_time_zone updatedAt
|
||||
}
|
||||
"public.mcp_server_tool" {
|
||||
timestamp_3__with_time_zone createdAt
|
||||
text description
|
||||
varchar_16_ draftSource
|
||||
uuid id
|
||||
varchar_16_ kind
|
||||
integer position
|
||||
uuid serverId FK
|
||||
varchar_36_ targetId
|
||||
json toolData
|
||||
varchar_64_ toolName
|
||||
timestamp_3__with_time_zone updatedAt
|
||||
}
|
||||
"public.user" {
|
||||
timestamp_3__with_time_zone createdAt
|
||||
boolean disabled
|
||||
varchar_255_ email
|
||||
varchar_32_ firstName
|
||||
uuid id
|
||||
varchar_16_ kind
|
||||
date lastActiveAt
|
||||
varchar_32_ lastName
|
||||
boolean mfaEnabled
|
||||
text mfaRecoveryCodes
|
||||
text mfaSecret
|
||||
varchar_255_ password
|
||||
json personalizationAnswers
|
||||
varchar_128_ roleSlug FK
|
||||
json settings
|
||||
timestamp_3__with_time_zone updatedAt
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
> Generated by [tbls](https://github.com/k1LoW/tbls)
|
||||
+18
-1
@@ -8,7 +8,7 @@
|
||||
| clientSecretExpiresAt | bigint | | true | | | |
|
||||
| createdAt | timestamp(3) with time zone | CURRENT_TIMESTAMP(3) | false | | | |
|
||||
| grantTypes | json | | false | | | |
|
||||
| id | varchar | | false | [public.mcp_server_connection](public.mcp_server_connection.md) [public.oauth_access_tokens](public.oauth_access_tokens.md) [public.oauth_authorization_codes](public.oauth_authorization_codes.md) [public.oauth_client_credential](public.oauth_client_credential.md) [public.oauth_refresh_tokens](public.oauth_refresh_tokens.md) [public.oauth_user_consents](public.oauth_user_consents.md) | | |
|
||||
| id | varchar | | false | [public.mcp_server_connection](public.mcp_server_connection.md) [public.mcp_server_tool_call](public.mcp_server_tool_call.md) [public.oauth_access_tokens](public.oauth_access_tokens.md) [public.oauth_authorization_codes](public.oauth_authorization_codes.md) [public.oauth_client_credential](public.oauth_client_credential.md) [public.oauth_refresh_tokens](public.oauth_refresh_tokens.md) [public.oauth_user_consents](public.oauth_user_consents.md) | | |
|
||||
| isFirstParty | boolean | false | false | | | |
|
||||
| name | varchar(255) | | false | | | |
|
||||
| redirectUris | json | | false | | | |
|
||||
@@ -45,6 +45,7 @@
|
||||
erDiagram
|
||||
|
||||
"public.mcp_server_connection" }o--|| "public.oauth_clients" : "FOREIGN KEY (#quot;oauthClientId#quot;) REFERENCES oauth_clients(id) ON DELETE CASCADE"
|
||||
"public.mcp_server_tool_call" }o--o| "public.oauth_clients" : "FOREIGN KEY (#quot;oauthClientId#quot;) REFERENCES oauth_clients(id) ON DELETE SET NULL"
|
||||
"public.oauth_access_tokens" }o--|| "public.oauth_clients" : "FOREIGN KEY (#quot;clientId#quot;) REFERENCES oauth_clients(id) ON DELETE CASCADE"
|
||||
"public.oauth_authorization_codes" }o--|| "public.oauth_clients" : "FOREIGN KEY (#quot;clientId#quot;) REFERENCES oauth_clients(id) ON DELETE CASCADE"
|
||||
"public.oauth_client_credential" }o--|| "public.oauth_clients" : "FOREIGN KEY (#quot;clientId#quot;) REFERENCES oauth_clients(id) ON DELETE CASCADE"
|
||||
@@ -73,6 +74,22 @@ erDiagram
|
||||
uuid serverId FK
|
||||
uuid userId FK
|
||||
}
|
||||
"public.mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
integer durationMs
|
||||
text errorMessage
|
||||
varchar_36_ executionId
|
||||
integer id
|
||||
varchar oauthClientId FK
|
||||
uuid serverId FK
|
||||
timestamp_3__with_time_zone startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
uuid toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
uuid userId FK
|
||||
}
|
||||
"public.oauth_access_tokens" {
|
||||
varchar clientId FK
|
||||
varchar resource
|
||||
|
||||
+18
-1
@@ -8,7 +8,7 @@
|
||||
| disabled | boolean | false | false | | | |
|
||||
| email | varchar(255) | | true | | | |
|
||||
| firstName | varchar(32) | | true | | | |
|
||||
| id | uuid | gen_random_uuid() | false | [public.activity_event](public.activity_event.md) [public.agent_eval_dataset](public.agent_eval_dataset.md) [public.agent_eval_rating](public.agent_eval_rating.md) [public.agent_eval_run](public.agent_eval_run.md) [public.agent_execution_threads](public.agent_execution_threads.md) [public.agent_history](public.agent_history.md) [public.agent_publish_history](public.agent_publish_history.md) [public.agents](public.agents.md) [public.ai_preference](public.ai_preference.md) [public.assistant_usage_event](public.assistant_usage_event.md) [public.auth_identity](public.auth_identity.md) [public.chat_hub_agents](public.chat_hub_agents.md) [public.chat_hub_sessions](public.chat_hub_sessions.md) [public.chat_hub_tools](public.chat_hub_tools.md) [public.dynamic_credential_user_entry](public.dynamic_credential_user_entry.md) [public.evaluation_collection](public.evaluation_collection.md) [public.idempotency_key](public.idempotency_key.md) [public.instance_ai_mcp_registry_connections](public.instance_ai_mcp_registry_connections.md) [public.instance_ai_pending_confirmations](public.instance_ai_pending_confirmations.md) [public.instance_ai_thread_grants](public.instance_ai_thread_grants.md) [public.instance_ai_thread_tabs](public.instance_ai_thread_tabs.md) [public.knowledge_collection](public.knowledge_collection.md) [public.knowledge_file](public.knowledge_file.md) [public.knowledge_vector_store](public.knowledge_vector_store.md) [public.mcp_server](public.mcp_server.md) [public.mcp_server_block](public.mcp_server_block.md) [public.mcp_server_connection](public.mcp_server_connection.md) [public.migration_workflow_owner](public.migration_workflow_owner.md) [public.oauth_access_tokens](public.oauth_access_tokens.md) [public.oauth_authorization_codes](public.oauth_authorization_codes.md) [public.oauth_client_credential](public.oauth_client_credential.md) [public.oauth_refresh_tokens](public.oauth_refresh_tokens.md) [public.oauth_user_consents](public.oauth_user_consents.md) [public.project](public.project.md) [public.project_relation](public.project_relation.md) [public.promotion_review](public.promotion_review.md) [public.promotion_run](public.promotion_run.md) [public.self_healing_configuration](public.self_healing_configuration.md) [public.self_healing_configuration_reviewer](public.self_healing_configuration_reviewer.md) [public.self_healing_investigation](public.self_healing_investigation.md) [public.self_healing_result](public.self_healing_result.md) [public.service_account_details](public.service_account_details.md) [public.skill](public.skill.md) [public.skill_source](public.skill_source.md) [public.skill_version](public.skill_version.md) [public.trusted_source_identity](public.trusted_source_identity.md) [public.user_api_keys](public.user_api_keys.md) [public.user_favorites](public.user_favorites.md) [public.workflow_builder_session](public.workflow_builder_session.md) [public.workflow_publish_history](public.workflow_publish_history.md) [public.workflow_review_activity](public.workflow_review_activity.md) [public.workflow_review_activity_comment](public.workflow_review_activity_comment.md) [public.workflow_review_request](public.workflow_review_request.md) [public.workflow_review_request_authors](public.workflow_review_request_authors.md) [public.workflow_review_request_reviewers](public.workflow_review_request_reviewers.md) [public.workflow_suggestion](public.workflow_suggestion.md) [public.workflow_suggestion_activity](public.workflow_suggestion_activity.md) | | |
|
||||
| id | uuid | gen_random_uuid() | false | [public.activity_event](public.activity_event.md) [public.agent_eval_dataset](public.agent_eval_dataset.md) [public.agent_eval_rating](public.agent_eval_rating.md) [public.agent_eval_run](public.agent_eval_run.md) [public.agent_execution_threads](public.agent_execution_threads.md) [public.agent_history](public.agent_history.md) [public.agent_publish_history](public.agent_publish_history.md) [public.agents](public.agents.md) [public.ai_preference](public.ai_preference.md) [public.assistant_usage_event](public.assistant_usage_event.md) [public.auth_identity](public.auth_identity.md) [public.chat_hub_agents](public.chat_hub_agents.md) [public.chat_hub_sessions](public.chat_hub_sessions.md) [public.chat_hub_tools](public.chat_hub_tools.md) [public.dynamic_credential_user_entry](public.dynamic_credential_user_entry.md) [public.evaluation_collection](public.evaluation_collection.md) [public.idempotency_key](public.idempotency_key.md) [public.instance_ai_mcp_registry_connections](public.instance_ai_mcp_registry_connections.md) [public.instance_ai_pending_confirmations](public.instance_ai_pending_confirmations.md) [public.instance_ai_thread_grants](public.instance_ai_thread_grants.md) [public.instance_ai_thread_tabs](public.instance_ai_thread_tabs.md) [public.knowledge_collection](public.knowledge_collection.md) [public.knowledge_file](public.knowledge_file.md) [public.knowledge_vector_store](public.knowledge_vector_store.md) [public.mcp_server](public.mcp_server.md) [public.mcp_server_block](public.mcp_server_block.md) [public.mcp_server_connection](public.mcp_server_connection.md) [public.mcp_server_tool_call](public.mcp_server_tool_call.md) [public.migration_workflow_owner](public.migration_workflow_owner.md) [public.oauth_access_tokens](public.oauth_access_tokens.md) [public.oauth_authorization_codes](public.oauth_authorization_codes.md) [public.oauth_client_credential](public.oauth_client_credential.md) [public.oauth_refresh_tokens](public.oauth_refresh_tokens.md) [public.oauth_user_consents](public.oauth_user_consents.md) [public.project](public.project.md) [public.project_relation](public.project_relation.md) [public.promotion_review](public.promotion_review.md) [public.promotion_run](public.promotion_run.md) [public.self_healing_configuration](public.self_healing_configuration.md) [public.self_healing_configuration_reviewer](public.self_healing_configuration_reviewer.md) [public.self_healing_investigation](public.self_healing_investigation.md) [public.self_healing_result](public.self_healing_result.md) [public.service_account_details](public.service_account_details.md) [public.skill](public.skill.md) [public.skill_source](public.skill_source.md) [public.skill_version](public.skill_version.md) [public.trusted_source_identity](public.trusted_source_identity.md) [public.user_api_keys](public.user_api_keys.md) [public.user_favorites](public.user_favorites.md) [public.workflow_builder_session](public.workflow_builder_session.md) [public.workflow_publish_history](public.workflow_publish_history.md) [public.workflow_review_activity](public.workflow_review_activity.md) [public.workflow_review_activity_comment](public.workflow_review_activity_comment.md) [public.workflow_review_request](public.workflow_review_request.md) [public.workflow_review_request_authors](public.workflow_review_request_authors.md) [public.workflow_review_request_reviewers](public.workflow_review_request_reviewers.md) [public.workflow_suggestion](public.workflow_suggestion.md) [public.workflow_suggestion_activity](public.workflow_suggestion_activity.md) | | |
|
||||
| kind | varchar(16) | 'person'::character varying | false | | | Kind of account: person or service |
|
||||
| lastActiveAt | date | | true | | | |
|
||||
| lastName | varchar(32) | | true | | | |
|
||||
@@ -79,6 +79,7 @@ erDiagram
|
||||
"public.mcp_server_block" }o--|| "public.user" : "FOREIGN KEY (#quot;userId#quot;) REFERENCES #quot;user#quot;(id) ON DELETE CASCADE"
|
||||
"public.mcp_server_block" }o--o| "public.user" : "FOREIGN KEY (#quot;blockedById#quot;) REFERENCES #quot;user#quot;(id) ON DELETE SET NULL"
|
||||
"public.mcp_server_connection" }o--|| "public.user" : "FOREIGN KEY (#quot;userId#quot;) REFERENCES #quot;user#quot;(id) ON DELETE CASCADE"
|
||||
"public.mcp_server_tool_call" }o--o| "public.user" : "FOREIGN KEY (#quot;userId#quot;) REFERENCES #quot;user#quot;(id) ON DELETE SET NULL"
|
||||
"public.migration_workflow_owner" }o--o| "public.user" : "FOREIGN KEY (#quot;userId#quot;) REFERENCES #quot;user#quot;(id) ON DELETE SET NULL"
|
||||
"public.migration_workflow_owner" }o--o| "public.user" : "FOREIGN KEY (#quot;assignedById#quot;) REFERENCES #quot;user#quot;(id) ON DELETE SET NULL"
|
||||
"public.oauth_access_tokens" }o--|| "public.user" : "FOREIGN KEY (#quot;userId#quot;) REFERENCES #quot;user#quot;(id) ON DELETE CASCADE"
|
||||
@@ -460,6 +461,22 @@ erDiagram
|
||||
uuid serverId FK
|
||||
uuid userId FK
|
||||
}
|
||||
"public.mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
integer durationMs
|
||||
text errorMessage
|
||||
varchar_36_ executionId
|
||||
integer id
|
||||
varchar oauthClientId FK
|
||||
uuid serverId FK
|
||||
timestamp_3__with_time_zone startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
uuid toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
uuid userId FK
|
||||
}
|
||||
"public.migration_workflow_owner" {
|
||||
timestamp_3__with_time_zone assignedAt
|
||||
uuid assignedById FK
|
||||
|
||||
Generated
+21
@@ -131,6 +131,7 @@ Auto-generated from the SQLite migrations in @n8n/db. Do not edit by hand.
|
||||
| [mcp_server_connection](mcp_server_connection.md) | 6 | | table |
|
||||
| [mcp_server_reserved_slug](mcp_server_reserved_slug.md) | 3 | | table |
|
||||
| [mcp_server_tool](mcp_server_tool.md) | 11 | | table |
|
||||
| [mcp_server_tool_call](mcp_server_tool_call.md) | 14 | | table |
|
||||
| [migration_finding](migration_finding.md) | 10 | | table |
|
||||
| [migration_finding_sync](migration_finding_sync.md) | 3 | | table |
|
||||
| [migration_workflow_owner](migration_workflow_owner.md) | 7 | | table |
|
||||
@@ -410,6 +411,10 @@ erDiagram
|
||||
"mcp_server_connection" |o--|| "mcp_server" : "FOREIGN KEY (serverId) REFERENCES mcp_server (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"mcp_server_reserved_slug" }o--|| "mcp_server" : "FOREIGN KEY (serverId) REFERENCES mcp_server (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"mcp_server_tool" }o--|| "mcp_server" : "FOREIGN KEY (serverId) REFERENCES mcp_server (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"mcp_server_tool_call" }o--o| "oauth_clients" : "FOREIGN KEY (oauthClientId) REFERENCES oauth_clients (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"mcp_server_tool_call" }o--o| "user" : "FOREIGN KEY (userId) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"mcp_server_tool_call" }o--o| "mcp_server_tool" : "FOREIGN KEY (toolId) REFERENCES mcp_server_tool (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"mcp_server_tool_call" }o--|| "mcp_server" : "FOREIGN KEY (serverId) REFERENCES mcp_server (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"migration_finding" }o--|| "workflow_entity" : "FOREIGN KEY (workflowId) REFERENCES workflow_entity (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"migration_workflow_owner" }o--o| "user" : "FOREIGN KEY (assignedById) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"migration_workflow_owner" }o--o| "user" : "FOREIGN KEY (userId) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
@@ -1826,6 +1831,22 @@ erDiagram
|
||||
varchar_64_ toolName
|
||||
datetime_3_ updatedAt
|
||||
}
|
||||
"mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
INTEGER durationMs
|
||||
TEXT errorMessage
|
||||
varchar_36_ executionId
|
||||
INTEGER id
|
||||
varchar oauthClientId FK
|
||||
varchar serverId FK
|
||||
datetime_3_ startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
varchar toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
varchar userId FK
|
||||
}
|
||||
"migration_finding" {
|
||||
datetime_3_ createdAt
|
||||
INTEGER id
|
||||
|
||||
+18
-1
@@ -19,7 +19,7 @@ CREATE TABLE "mcp_server" ("id" varchar PRIMARY KEY NOT NULL, "projectId" varcha
|
||||
| createdById | varchar | | true | | [user](user.md) | |
|
||||
| deletedAt | datetime(3) | | true | | | |
|
||||
| description | TEXT | '' | false | | | |
|
||||
| id | varchar | | false | [mcp_server_block](mcp_server_block.md) [mcp_server_connection](mcp_server_connection.md) [mcp_server_reserved_slug](mcp_server_reserved_slug.md) [mcp_server_tool](mcp_server_tool.md) | | |
|
||||
| id | varchar | | false | [mcp_server_block](mcp_server_block.md) [mcp_server_connection](mcp_server_connection.md) [mcp_server_reserved_slug](mcp_server_reserved_slug.md) [mcp_server_tool](mcp_server_tool.md) [mcp_server_tool_call](mcp_server_tool_call.md) | | |
|
||||
| name | varchar(128) | | false | | | |
|
||||
| projectId | varchar(36) | | false | | [project](project.md) | |
|
||||
| slug | varchar(128) | | false | | | |
|
||||
@@ -53,6 +53,7 @@ erDiagram
|
||||
"mcp_server_connection" |o--|| "mcp_server" : "FOREIGN KEY (serverId) REFERENCES mcp_server (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"mcp_server_reserved_slug" }o--|| "mcp_server" : "FOREIGN KEY (serverId) REFERENCES mcp_server (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"mcp_server_tool" }o--|| "mcp_server" : "FOREIGN KEY (serverId) REFERENCES mcp_server (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"mcp_server_tool_call" }o--|| "mcp_server" : "FOREIGN KEY (serverId) REFERENCES mcp_server (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"mcp_server" }o--|| "project" : "FOREIGN KEY (projectId) REFERENCES project (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
|
||||
"mcp_server" {
|
||||
@@ -116,6 +117,22 @@ erDiagram
|
||||
varchar_64_ toolName
|
||||
datetime_3_ updatedAt
|
||||
}
|
||||
"mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
INTEGER durationMs
|
||||
TEXT errorMessage
|
||||
varchar_36_ executionId
|
||||
INTEGER id
|
||||
varchar oauthClientId FK
|
||||
varchar serverId FK
|
||||
datetime_3_ startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
varchar toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
varchar userId FK
|
||||
}
|
||||
"project" {
|
||||
datetime_3_ createdAt
|
||||
varchar creatorId FK
|
||||
|
||||
+18
-1
@@ -18,7 +18,7 @@ CREATE TABLE "mcp_server_tool" ("id" varchar PRIMARY KEY NOT NULL, "serverId" va
|
||||
| createdAt | datetime(3) | STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') | false | | | |
|
||||
| description | TEXT | '' | false | | | |
|
||||
| draftSource | varchar(16) | 'defaults' | false | | | |
|
||||
| id | varchar | | false | | | |
|
||||
| id | varchar | | false | [mcp_server_tool_call](mcp_server_tool_call.md) | | |
|
||||
| kind | varchar(16) | | false | | | |
|
||||
| position | INTEGER | 0 | false | | | |
|
||||
| serverId | varchar | | false | | [mcp_server](mcp_server.md) | |
|
||||
@@ -49,6 +49,7 @@ CREATE TABLE "mcp_server_tool" ("id" varchar PRIMARY KEY NOT NULL, "serverId" va
|
||||
```mermaid
|
||||
erDiagram
|
||||
|
||||
"mcp_server_tool_call" }o--o| "mcp_server_tool" : "FOREIGN KEY (toolId) REFERENCES mcp_server_tool (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"mcp_server_tool" }o--|| "mcp_server" : "FOREIGN KEY (serverId) REFERENCES mcp_server (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
|
||||
"mcp_server_tool" {
|
||||
@@ -64,6 +65,22 @@ erDiagram
|
||||
varchar_64_ toolName
|
||||
datetime_3_ updatedAt
|
||||
}
|
||||
"mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
INTEGER durationMs
|
||||
TEXT errorMessage
|
||||
varchar_36_ executionId
|
||||
INTEGER id
|
||||
varchar oauthClientId FK
|
||||
varchar serverId FK
|
||||
datetime_3_ startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
varchar toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
varchar userId FK
|
||||
}
|
||||
"mcp_server" {
|
||||
datetime_3_ createdAt
|
||||
varchar createdById FK
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
# mcp_server_tool_call
|
||||
|
||||
## Description
|
||||
|
||||
<details>
|
||||
<summary><strong>Table Definition</strong></summary>
|
||||
|
||||
```sql
|
||||
CREATE TABLE "mcp_server_tool_call" ("id" integer PRIMARY KEY NOT NULL, "serverId" varchar NOT NULL, "toolId" varchar, "toolName" varchar(64) NOT NULL, "toolKind" varchar(16) NOT NULL, "targetId" varchar(36), "userId" varchar, "oauthClientId" varchar, "clientName" varchar(255) NOT NULL, "status" varchar(16) NOT NULL, "durationMs" integer NOT NULL, "executionId" varchar(36), "errorMessage" text, "startedAt" datetime(3) NOT NULL DEFAULT (STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')), CONSTRAINT "CHK_mcp_server_tool_call_toolKind" CHECK ("toolKind" IN ('workflow', 'node', 'agent', 'skill')), CONSTRAINT "CHK_mcp_server_tool_call_status" CHECK ("status" IN ('success', 'error', 'unfinished')), CONSTRAINT "FK_44f4821858f73c1871d000f8e7a" FOREIGN KEY ("serverId") REFERENCES "mcp_server" ("id") ON DELETE CASCADE, CONSTRAINT "FK_18ad188e9975d252128e1097007" FOREIGN KEY ("toolId") REFERENCES "mcp_server_tool" ("id") ON DELETE SET NULL, CONSTRAINT "FK_6c1ca8e2b27fda7624b2e0888d7" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE SET NULL, CONSTRAINT "FK_29fac15a0c61fd77fe2c0b5bf44" FOREIGN KEY ("oauthClientId") REFERENCES "oauth_clients" ("id") ON DELETE SET NULL)
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## Columns
|
||||
|
||||
| Name | Type | Default | Nullable | Children | Parents | Comment |
|
||||
| ---- | ---- | ------- | -------- | -------- | ------- | ------- |
|
||||
| clientName | varchar(255) | | false | | | |
|
||||
| durationMs | INTEGER | | false | | | |
|
||||
| errorMessage | TEXT | | true | | | |
|
||||
| executionId | varchar(36) | | true | | | |
|
||||
| id | INTEGER | | false | | | |
|
||||
| oauthClientId | varchar | | true | | [oauth_clients](oauth_clients.md) | |
|
||||
| serverId | varchar | | false | | [mcp_server](mcp_server.md) | |
|
||||
| startedAt | datetime(3) | STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') | false | | | |
|
||||
| status | varchar(16) | | false | | | |
|
||||
| targetId | varchar(36) | | true | | | |
|
||||
| toolId | varchar | | true | | [mcp_server_tool](mcp_server_tool.md) | |
|
||||
| toolKind | varchar(16) | | false | | | |
|
||||
| toolName | varchar(64) | | false | | | |
|
||||
| userId | varchar | | true | | [user](user.md) | |
|
||||
|
||||
## Constraints
|
||||
|
||||
| Name | Type | Definition |
|
||||
| ---- | ---- | ---------- |
|
||||
| - | CHECK | CHECK ("toolKind" IN ('workflow', 'node', 'agent', 'skill')) |
|
||||
| - | CHECK | CHECK ("status" IN ('success', 'error', 'unfinished')) |
|
||||
| - (Foreign key ID: 0) | FOREIGN KEY | FOREIGN KEY (oauthClientId) REFERENCES oauth_clients (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE |
|
||||
| - (Foreign key ID: 1) | FOREIGN KEY | FOREIGN KEY (userId) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE |
|
||||
| - (Foreign key ID: 2) | FOREIGN KEY | FOREIGN KEY (toolId) REFERENCES mcp_server_tool (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE |
|
||||
| - (Foreign key ID: 3) | FOREIGN KEY | FOREIGN KEY (serverId) REFERENCES mcp_server (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE |
|
||||
| id | PRIMARY KEY | PRIMARY KEY (id) |
|
||||
|
||||
## Indexes
|
||||
|
||||
| Name | Definition |
|
||||
| ---- | ---------- |
|
||||
| IDX_110df42f5591dbb48d0bbda4ec | CREATE INDEX "IDX_110df42f5591dbb48d0bbda4ec" ON "mcp_server_tool_call" ("serverId", "startedAt", "id") |
|
||||
| IDX_18ad188e9975d252128e109700 | CREATE INDEX "IDX_18ad188e9975d252128e109700" ON "mcp_server_tool_call" ("toolId") |
|
||||
| IDX_29fac15a0c61fd77fe2c0b5bf4 | CREATE INDEX "IDX_29fac15a0c61fd77fe2c0b5bf4" ON "mcp_server_tool_call" ("oauthClientId") |
|
||||
| IDX_44155d3ec8733193ec47d233ac | CREATE INDEX "IDX_44155d3ec8733193ec47d233ac" ON "mcp_server_tool_call" ("serverId", "status", "id") |
|
||||
| IDX_6c1ca8e2b27fda7624b2e0888d | CREATE INDEX "IDX_6c1ca8e2b27fda7624b2e0888d" ON "mcp_server_tool_call" ("userId") |
|
||||
| IDX_7f42993460a22186d3c6e6926b | CREATE INDEX "IDX_7f42993460a22186d3c6e6926b" ON "mcp_server_tool_call" ("serverId", "durationMs", "id") |
|
||||
| IDX_8e6ac48653f0e81a3a1c2adb2e | CREATE INDEX "IDX_8e6ac48653f0e81a3a1c2adb2e" ON "mcp_server_tool_call" ("startedAt") |
|
||||
| IDX_d9f0af248f53a307dda2cb3001 | CREATE INDEX "IDX_d9f0af248f53a307dda2cb3001" ON "mcp_server_tool_call" ("serverId", "toolName", "id") |
|
||||
|
||||
## Relations
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
|
||||
"mcp_server_tool_call" }o--o| "oauth_clients" : "FOREIGN KEY (oauthClientId) REFERENCES oauth_clients (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"mcp_server_tool_call" }o--|| "mcp_server" : "FOREIGN KEY (serverId) REFERENCES mcp_server (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"mcp_server_tool_call" }o--o| "mcp_server_tool" : "FOREIGN KEY (toolId) REFERENCES mcp_server_tool (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"mcp_server_tool_call" }o--o| "user" : "FOREIGN KEY (userId) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
|
||||
"mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
INTEGER durationMs
|
||||
TEXT errorMessage
|
||||
varchar_36_ executionId
|
||||
INTEGER id
|
||||
varchar oauthClientId FK
|
||||
varchar serverId FK
|
||||
datetime_3_ startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
varchar toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
varchar userId FK
|
||||
}
|
||||
"oauth_clients" {
|
||||
varchar_255_ clientSecret
|
||||
bigint clientSecretExpiresAt
|
||||
datetime_3_ createdAt
|
||||
TEXT grantTypes
|
||||
varchar id PK
|
||||
boolean isFirstParty
|
||||
varchar_255_ name
|
||||
TEXT redirectUris
|
||||
VARCHAR serviceAccountId FK
|
||||
varchar_255_ tokenEndpointAuthMethod
|
||||
datetime_3_ updatedAt
|
||||
}
|
||||
"mcp_server" {
|
||||
datetime_3_ createdAt
|
||||
varchar createdById FK
|
||||
datetime_3_ deletedAt
|
||||
TEXT description
|
||||
varchar id PK
|
||||
varchar_128_ name
|
||||
varchar_36_ projectId FK
|
||||
varchar_128_ slug
|
||||
datetime_3_ updatedAt
|
||||
}
|
||||
"mcp_server_tool" {
|
||||
datetime_3_ createdAt
|
||||
TEXT description
|
||||
varchar_16_ draftSource
|
||||
varchar id PK
|
||||
varchar_16_ kind
|
||||
INTEGER position
|
||||
varchar serverId FK
|
||||
varchar_36_ targetId
|
||||
TEXT toolData
|
||||
varchar_64_ toolName
|
||||
datetime_3_ updatedAt
|
||||
}
|
||||
"user" {
|
||||
datetime_3_ createdAt
|
||||
boolean disabled
|
||||
varchar_255_ email
|
||||
varchar_32_ firstName
|
||||
varchar id PK
|
||||
VARCHAR_16_ kind
|
||||
date lastActiveAt
|
||||
varchar_32_ lastName
|
||||
boolean mfaEnabled
|
||||
TEXT mfaRecoveryCodes
|
||||
TEXT mfaSecret
|
||||
varchar password
|
||||
TEXT personalizationAnswers
|
||||
varchar_128_ roleSlug FK
|
||||
TEXT settings
|
||||
datetime_3_ updatedAt
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
> Generated by [tbls](https://github.com/k1LoW/tbls)
|
||||
+18
-1
@@ -19,7 +19,7 @@ CREATE TABLE "oauth_clients" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar(
|
||||
| clientSecretExpiresAt | bigint | | true | | | |
|
||||
| createdAt | datetime(3) | STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') | false | | | |
|
||||
| grantTypes | TEXT | | false | | | |
|
||||
| id | varchar | | false | [mcp_server_connection](mcp_server_connection.md) [oauth_access_tokens](oauth_access_tokens.md) [oauth_authorization_codes](oauth_authorization_codes.md) [oauth_client_credential](oauth_client_credential.md) [oauth_refresh_tokens](oauth_refresh_tokens.md) [oauth_user_consents](oauth_user_consents.md) | | |
|
||||
| id | varchar | | false | [mcp_server_connection](mcp_server_connection.md) [mcp_server_tool_call](mcp_server_tool_call.md) [oauth_access_tokens](oauth_access_tokens.md) [oauth_authorization_codes](oauth_authorization_codes.md) [oauth_client_credential](oauth_client_credential.md) [oauth_refresh_tokens](oauth_refresh_tokens.md) [oauth_user_consents](oauth_user_consents.md) | | |
|
||||
| isFirstParty | boolean | false | false | | | |
|
||||
| name | varchar(255) | | false | | | |
|
||||
| redirectUris | TEXT | | false | | | |
|
||||
@@ -49,6 +49,7 @@ CREATE TABLE "oauth_clients" ("id" varchar PRIMARY KEY NOT NULL, "name" varchar(
|
||||
erDiagram
|
||||
|
||||
"mcp_server_connection" |o--|| "oauth_clients" : "FOREIGN KEY (oauthClientId) REFERENCES oauth_clients (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"mcp_server_tool_call" }o--o| "oauth_clients" : "FOREIGN KEY (oauthClientId) REFERENCES oauth_clients (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"oauth_access_tokens" }o--|| "oauth_clients" : "FOREIGN KEY (clientId) REFERENCES oauth_clients (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"oauth_authorization_codes" }o--|| "oauth_clients" : "FOREIGN KEY (clientId) REFERENCES oauth_clients (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"oauth_client_credential" }o--|| "oauth_clients" : "FOREIGN KEY (clientId) REFERENCES oauth_clients (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
@@ -77,6 +78,22 @@ erDiagram
|
||||
varchar serverId PK
|
||||
varchar userId PK
|
||||
}
|
||||
"mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
INTEGER durationMs
|
||||
TEXT errorMessage
|
||||
varchar_36_ executionId
|
||||
INTEGER id
|
||||
varchar oauthClientId FK
|
||||
varchar serverId FK
|
||||
datetime_3_ startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
varchar toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
varchar userId FK
|
||||
}
|
||||
"oauth_access_tokens" {
|
||||
varchar clientId FK
|
||||
VARCHAR resource
|
||||
|
||||
Generated
+18
-1
@@ -19,7 +19,7 @@ CREATE TABLE "user" ("id" varchar PRIMARY KEY, "email" varchar(255), "firstName"
|
||||
| disabled | boolean | FALSE | false | | | |
|
||||
| email | varchar(255) | | true | | | |
|
||||
| firstName | varchar(32) | | true | | | |
|
||||
| id | varchar | | true | [activity_event](activity_event.md) [agent_eval_dataset](agent_eval_dataset.md) [agent_eval_rating](agent_eval_rating.md) [agent_eval_run](agent_eval_run.md) [agent_execution_threads](agent_execution_threads.md) [agent_history](agent_history.md) [agent_publish_history](agent_publish_history.md) [agents](agents.md) [ai_preference](ai_preference.md) [assistant_usage_event](assistant_usage_event.md) [auth_identity](auth_identity.md) [chat_hub_agents](chat_hub_agents.md) [chat_hub_sessions](chat_hub_sessions.md) [chat_hub_tools](chat_hub_tools.md) [dynamic_credential_user_entry](dynamic_credential_user_entry.md) [evaluation_collection](evaluation_collection.md) [idempotency_key](idempotency_key.md) [instance_ai_mcp_registry_connections](instance_ai_mcp_registry_connections.md) [instance_ai_pending_confirmations](instance_ai_pending_confirmations.md) [instance_ai_thread_grants](instance_ai_thread_grants.md) [instance_ai_thread_tabs](instance_ai_thread_tabs.md) [knowledge_collection](knowledge_collection.md) [knowledge_file](knowledge_file.md) [knowledge_vector_store](knowledge_vector_store.md) [mcp_server](mcp_server.md) [mcp_server_block](mcp_server_block.md) [mcp_server_connection](mcp_server_connection.md) [migration_workflow_owner](migration_workflow_owner.md) [oauth_access_tokens](oauth_access_tokens.md) [oauth_authorization_codes](oauth_authorization_codes.md) [oauth_client_credential](oauth_client_credential.md) [oauth_refresh_tokens](oauth_refresh_tokens.md) [oauth_user_consents](oauth_user_consents.md) [project](project.md) [project_relation](project_relation.md) [promotion_review](promotion_review.md) [promotion_run](promotion_run.md) [self_healing_configuration](self_healing_configuration.md) [self_healing_configuration_reviewer](self_healing_configuration_reviewer.md) [self_healing_investigation](self_healing_investigation.md) [self_healing_result](self_healing_result.md) [service_account_details](service_account_details.md) [skill](skill.md) [skill_source](skill_source.md) [skill_version](skill_version.md) [trusted_source_identity](trusted_source_identity.md) [user_api_keys](user_api_keys.md) [user_favorites](user_favorites.md) [workflow_builder_session](workflow_builder_session.md) [workflow_publish_history](workflow_publish_history.md) [workflow_review_activity](workflow_review_activity.md) [workflow_review_activity_comment](workflow_review_activity_comment.md) [workflow_review_request](workflow_review_request.md) [workflow_review_request_authors](workflow_review_request_authors.md) [workflow_review_request_reviewers](workflow_review_request_reviewers.md) [workflow_suggestion](workflow_suggestion.md) [workflow_suggestion_activity](workflow_suggestion_activity.md) | | |
|
||||
| id | varchar | | true | [activity_event](activity_event.md) [agent_eval_dataset](agent_eval_dataset.md) [agent_eval_rating](agent_eval_rating.md) [agent_eval_run](agent_eval_run.md) [agent_execution_threads](agent_execution_threads.md) [agent_history](agent_history.md) [agent_publish_history](agent_publish_history.md) [agents](agents.md) [ai_preference](ai_preference.md) [assistant_usage_event](assistant_usage_event.md) [auth_identity](auth_identity.md) [chat_hub_agents](chat_hub_agents.md) [chat_hub_sessions](chat_hub_sessions.md) [chat_hub_tools](chat_hub_tools.md) [dynamic_credential_user_entry](dynamic_credential_user_entry.md) [evaluation_collection](evaluation_collection.md) [idempotency_key](idempotency_key.md) [instance_ai_mcp_registry_connections](instance_ai_mcp_registry_connections.md) [instance_ai_pending_confirmations](instance_ai_pending_confirmations.md) [instance_ai_thread_grants](instance_ai_thread_grants.md) [instance_ai_thread_tabs](instance_ai_thread_tabs.md) [knowledge_collection](knowledge_collection.md) [knowledge_file](knowledge_file.md) [knowledge_vector_store](knowledge_vector_store.md) [mcp_server](mcp_server.md) [mcp_server_block](mcp_server_block.md) [mcp_server_connection](mcp_server_connection.md) [mcp_server_tool_call](mcp_server_tool_call.md) [migration_workflow_owner](migration_workflow_owner.md) [oauth_access_tokens](oauth_access_tokens.md) [oauth_authorization_codes](oauth_authorization_codes.md) [oauth_client_credential](oauth_client_credential.md) [oauth_refresh_tokens](oauth_refresh_tokens.md) [oauth_user_consents](oauth_user_consents.md) [project](project.md) [project_relation](project_relation.md) [promotion_review](promotion_review.md) [promotion_run](promotion_run.md) [self_healing_configuration](self_healing_configuration.md) [self_healing_configuration_reviewer](self_healing_configuration_reviewer.md) [self_healing_investigation](self_healing_investigation.md) [self_healing_result](self_healing_result.md) [service_account_details](service_account_details.md) [skill](skill.md) [skill_source](skill_source.md) [skill_version](skill_version.md) [trusted_source_identity](trusted_source_identity.md) [user_api_keys](user_api_keys.md) [user_favorites](user_favorites.md) [workflow_builder_session](workflow_builder_session.md) [workflow_publish_history](workflow_publish_history.md) [workflow_review_activity](workflow_review_activity.md) [workflow_review_activity_comment](workflow_review_activity_comment.md) [workflow_review_request](workflow_review_request.md) [workflow_review_request_authors](workflow_review_request_authors.md) [workflow_review_request_reviewers](workflow_review_request_reviewers.md) [workflow_suggestion](workflow_suggestion.md) [workflow_suggestion_activity](workflow_suggestion_activity.md) | | |
|
||||
| kind | VARCHAR(16) | 'person' | false | | | |
|
||||
| lastActiveAt | date | | true | | | |
|
||||
| lastName | varchar(32) | | true | | | |
|
||||
@@ -83,6 +83,7 @@ erDiagram
|
||||
"mcp_server_block" }o--o| "user" : "FOREIGN KEY (blockedById) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"mcp_server_block" |o--|| "user" : "FOREIGN KEY (userId) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"mcp_server_connection" |o--|| "user" : "FOREIGN KEY (userId) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
"mcp_server_tool_call" }o--o| "user" : "FOREIGN KEY (userId) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"migration_workflow_owner" }o--o| "user" : "FOREIGN KEY (assignedById) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"migration_workflow_owner" }o--o| "user" : "FOREIGN KEY (userId) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE SET NULL MATCH NONE"
|
||||
"oauth_access_tokens" }o--|| "user" : "FOREIGN KEY (userId) REFERENCES user (id) ON UPDATE NO ACTION ON DELETE CASCADE MATCH NONE"
|
||||
@@ -464,6 +465,22 @@ erDiagram
|
||||
varchar serverId PK
|
||||
varchar userId PK
|
||||
}
|
||||
"mcp_server_tool_call" {
|
||||
varchar_255_ clientName
|
||||
INTEGER durationMs
|
||||
TEXT errorMessage
|
||||
varchar_36_ executionId
|
||||
INTEGER id
|
||||
varchar oauthClientId FK
|
||||
varchar serverId FK
|
||||
datetime_3_ startedAt
|
||||
varchar_16_ status
|
||||
varchar_36_ targetId
|
||||
varchar toolId FK
|
||||
varchar_16_ toolKind
|
||||
varchar_64_ toolName
|
||||
varchar userId FK
|
||||
}
|
||||
"migration_workflow_owner" {
|
||||
datetime_3_ assignedAt
|
||||
varchar assignedById FK
|
||||
|
||||
@@ -19,6 +19,12 @@ export { DraftMcpServerAgentToolDto } from './mcp-server/draft-mcp-server-agent-
|
||||
export { AddMcpServerNodeToolDto } from './mcp-server/add-mcp-server-node-tool.dto';
|
||||
export { UpdateMcpServerNodeToolDto } from './mcp-server/update-mcp-server-node-tool.dto';
|
||||
export { BlockMcpServerUserDto } from './mcp-server/block-mcp-server-user.dto';
|
||||
export {
|
||||
ListMcpServerToolCallsDto,
|
||||
MCP_SERVER_TOOL_CALLS_DEFAULT_LIMIT,
|
||||
MCP_SERVER_TOOL_CALLS_MAX_LIMIT,
|
||||
MCP_SERVER_TOOL_CALLS_MAX_ROWS,
|
||||
} from './mcp-server/list-mcp-server-tool-calls.dto';
|
||||
|
||||
export { AiChatRequestDto } from './ai/ai-chat-request.dto';
|
||||
export type {
|
||||
|
||||
@@ -10,6 +10,11 @@ import { CreateMcpServerDto } from '../create-mcp-server.dto';
|
||||
import { DraftMcpServerAgentToolDto } from '../draft-mcp-server-agent-tool.dto';
|
||||
import { DraftMcpServerToolDto } from '../draft-mcp-server-tool.dto';
|
||||
import { DraftMcpServerWorkflowToolDto } from '../draft-mcp-server-workflow-tool.dto';
|
||||
import {
|
||||
ListMcpServerToolCallsDto,
|
||||
MCP_SERVER_TOOL_CALLS_DEFAULT_LIMIT,
|
||||
MCP_SERVER_TOOL_CALLS_MAX_LIMIT,
|
||||
} from '../list-mcp-server-tool-calls.dto';
|
||||
import { UpdateMcpServerToolDto } from '../update-mcp-server-tool.dto';
|
||||
import { UpdateMcpServerDto } from '../update-mcp-server.dto';
|
||||
|
||||
@@ -355,4 +360,50 @@ describe('MCP server DTOs', () => {
|
||||
expect(BlockMcpServerUserDto.safeParse({ userId }).success).toBe(true);
|
||||
expect(BlockMcpServerUserDto.safeParse({ userId: 'someone' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('parses tool call log query filters, sorting, and pagination', () => {
|
||||
const userId = '0190a8d6-4a2e-7000-8000-0000000000d1';
|
||||
expect(ListMcpServerToolCallsDto.parse({})).toEqual({
|
||||
sortBy: 'startedAt',
|
||||
sortDirection: 'desc',
|
||||
limit: MCP_SERVER_TOOL_CALLS_DEFAULT_LIMIT,
|
||||
offset: 0,
|
||||
});
|
||||
expect(
|
||||
ListMcpServerToolCallsDto.parse({
|
||||
toolName: ' get_pipeline ',
|
||||
userId,
|
||||
status: 'error',
|
||||
startedAfter: '2026-11-24T10:00:00.000Z',
|
||||
startedBefore: '2026-11-25T10:00:00+02:00',
|
||||
sortBy: 'durationMs',
|
||||
sortDirection: 'asc',
|
||||
limit: '50',
|
||||
offset: '25',
|
||||
}),
|
||||
).toEqual({
|
||||
toolName: 'get_pipeline',
|
||||
userId,
|
||||
status: 'error',
|
||||
startedAfter: '2026-11-24T10:00:00.000Z',
|
||||
startedBefore: '2026-11-25T10:00:00+02:00',
|
||||
sortBy: 'durationMs',
|
||||
sortDirection: 'asc',
|
||||
limit: 50,
|
||||
offset: 25,
|
||||
});
|
||||
|
||||
expect(ListMcpServerToolCallsDto.safeParse({ status: 'running' }).success).toBe(false);
|
||||
expect(ListMcpServerToolCallsDto.safeParse({ sortBy: 'caller' }).success).toBe(false);
|
||||
expect(ListMcpServerToolCallsDto.safeParse({ sortDirection: 'up' }).success).toBe(false);
|
||||
expect(ListMcpServerToolCallsDto.safeParse({ userId: 'not-a-uuid' }).success).toBe(false);
|
||||
expect(ListMcpServerToolCallsDto.safeParse({ startedAfter: 'yesterday' }).success).toBe(false);
|
||||
expect(ListMcpServerToolCallsDto.safeParse({ limit: 0 }).success).toBe(false);
|
||||
expect(
|
||||
ListMcpServerToolCallsDto.safeParse({ limit: MCP_SERVER_TOOL_CALLS_MAX_LIMIT + 1 }).success,
|
||||
).toBe(false);
|
||||
expect(ListMcpServerToolCallsDto.safeParse({ offset: -1 }).success).toBe(false);
|
||||
expect(ListMcpServerToolCallsDto.safeParse({ offset: 10_000 }).success).toBe(true);
|
||||
expect(ListMcpServerToolCallsDto.safeParse({ offset: 10_001 }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import {
|
||||
MCP_SERVER_TOOL_NAME_MAX_LENGTH,
|
||||
mcpServerToolCallSortBySchema,
|
||||
mcpServerToolCallSortDirectionSchema,
|
||||
mcpServerToolCallStatusSchema,
|
||||
} from '../../schemas/mcp-server.schema';
|
||||
import { Z } from '../../zod-class';
|
||||
|
||||
export const MCP_SERVER_TOOL_CALLS_DEFAULT_LIMIT = 25;
|
||||
export const MCP_SERVER_TOOL_CALLS_MAX_LIMIT = 100;
|
||||
/** Paging reaches the first 10,000 matching calls in the chosen sort order. `total` stops here too. */
|
||||
export const MCP_SERVER_TOOL_CALLS_MAX_ROWS = 10_000;
|
||||
|
||||
export class ListMcpServerToolCallsDto extends Z.class({
|
||||
toolName: z.string().trim().min(1).max(MCP_SERVER_TOOL_NAME_MAX_LENGTH).optional(),
|
||||
userId: z.string().uuid().optional(),
|
||||
status: mcpServerToolCallStatusSchema.optional(),
|
||||
startedAfter: z.string().datetime({ offset: true }).optional(),
|
||||
startedBefore: z.string().datetime({ offset: true }).optional(),
|
||||
sortBy: mcpServerToolCallSortBySchema.default('startedAt'),
|
||||
sortDirection: mcpServerToolCallSortDirectionSchema.default('desc'),
|
||||
limit: z.coerce
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(MCP_SERVER_TOOL_CALLS_MAX_LIMIT)
|
||||
.default(MCP_SERVER_TOOL_CALLS_DEFAULT_LIMIT),
|
||||
offset: z.coerce.number().int().min(0).max(MCP_SERVER_TOOL_CALLS_MAX_ROWS).default(0),
|
||||
}) {}
|
||||
@@ -536,6 +536,53 @@ export const mcpServerConnectionsResponseSchema = z.object({
|
||||
});
|
||||
export type McpServerConnectionsResponse = z.infer<typeof mcpServerConnectionsResponseSchema>;
|
||||
|
||||
/** `unfinished`: the run was still going when the call stopped waiting for it. */
|
||||
export const mcpServerToolCallStatusSchema = z.enum(['success', 'error', 'unfinished']);
|
||||
export type McpServerToolCallStatus = z.infer<typeof mcpServerToolCallStatusSchema>;
|
||||
|
||||
export const mcpServerToolCallSortBySchema = z.enum([
|
||||
'startedAt',
|
||||
'durationMs',
|
||||
'toolName',
|
||||
'status',
|
||||
]);
|
||||
export type McpServerToolCallSortBy = z.infer<typeof mcpServerToolCallSortBySchema>;
|
||||
|
||||
export const mcpServerToolCallSortDirectionSchema = z.enum(['asc', 'desc']);
|
||||
export type McpServerToolCallSortDirection = z.infer<typeof mcpServerToolCallSortDirectionSchema>;
|
||||
|
||||
/** One logged tool call on a custom MCP server. */
|
||||
export const mcpServerToolCallSchema = z.object({
|
||||
id: z.number().int(),
|
||||
toolId: z.string().uuid().nullable(),
|
||||
toolName: z.string(),
|
||||
toolKind: mcpServerToolKindSchema,
|
||||
targetId: z.string().nullable(),
|
||||
/** `null` when the user who made the call was deleted. */
|
||||
caller: mcpServerPersonSchema.nullable(),
|
||||
clientName: z.string(),
|
||||
status: mcpServerToolCallStatusSchema,
|
||||
durationMs: z.number().int().nonnegative(),
|
||||
/** Workflow execution ID when a workflow run started. `null` otherwise. */
|
||||
executionId: z.string().nullable(),
|
||||
/** Safe error summary returned to the client on failure. `null` on success. */
|
||||
errorMessage: z.string().nullable(),
|
||||
startedAt: z.string().datetime(),
|
||||
});
|
||||
export type McpServerToolCallResponse = z.infer<typeof mcpServerToolCallSchema>;
|
||||
|
||||
export const mcpServerToolCallsResponseSchema = z.object({
|
||||
items: z.array(mcpServerToolCallSchema),
|
||||
/** Number of matching calls, at most `MCP_SERVER_TOOL_CALLS_MAX_ROWS`. */
|
||||
total: z.number().int().nonnegative(),
|
||||
/** Distinct tools and callers available to filter on for this server. */
|
||||
filters: z.object({
|
||||
tools: z.array(z.string()),
|
||||
callers: z.array(mcpServerPersonSchema),
|
||||
}),
|
||||
});
|
||||
export type McpServerToolCallsResponse = z.infer<typeof mcpServerToolCallsResponseSchema>;
|
||||
|
||||
/** Where a builder action came from. Telemetry and the Assistant tool use it. */
|
||||
export const mcpServerActionSourceSchema = z.enum(['ui', 'assistant']);
|
||||
export type McpServerActionSource = z.infer<typeof mcpServerActionSourceSchema>;
|
||||
@@ -558,6 +605,7 @@ export const MCP_SERVER_ACTION_SCOPES = {
|
||||
draftTool: 'mcpServer:update',
|
||||
removeTool: 'mcpServer:update',
|
||||
listConnections: 'mcpServer:read',
|
||||
listToolCalls: 'mcpServer:read',
|
||||
// Block, restore access, and remove change who can use the server.
|
||||
blockPerson: 'mcpServer:update',
|
||||
restoreAccess: 'mcpServer:update',
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { MigrationContext, ReversibleMigration } from '../migration-types';
|
||||
|
||||
const toolCallTable = 'mcp_server_tool_call';
|
||||
const serverTable = 'mcp_server';
|
||||
const toolTable = 'mcp_server_tool';
|
||||
|
||||
/**
|
||||
* Tool call log for custom MCP servers: each row records one tool call made by an AI client
|
||||
* through a custom MCP server, including who called it, which tool ran, how long it took,
|
||||
* and its outcome.
|
||||
*/
|
||||
export class CreateMcpServerToolCallTable1796327881234 implements ReversibleMigration {
|
||||
async up({ schemaBuilder: { createTable, column } }: MigrationContext) {
|
||||
await createTable(toolCallTable)
|
||||
.withColumns(
|
||||
column('id').int.primary.autoGenerate2,
|
||||
column('serverId').uuid.notNull,
|
||||
column('toolId').uuid.comment('Tool row at call time. NULL when the tool was removed'),
|
||||
column('toolName').varchar(64).notNull.comment('Snapshot of the tool name at call time'),
|
||||
column('toolKind')
|
||||
.varchar(16)
|
||||
.notNull.withEnumCheck(['workflow', 'node', 'agent', 'skill'])
|
||||
.comment('What the tool ran: a workflow, a node, an agent, or a skill'),
|
||||
// No foreign key: the target table depends on `toolKind` and a log row outlives its target.
|
||||
column('targetId')
|
||||
.varchar(36)
|
||||
.comment('ID of the target workflow, agent, or skill at call time. NULL for a node tool'),
|
||||
column('userId').uuid.comment('Person who called the tool. NULL after the user is deleted'),
|
||||
column('oauthClientId')
|
||||
.varchar()
|
||||
.comment('OAuth client that called the tool. NULL when unavailable or deleted'),
|
||||
column('clientName')
|
||||
.varchar(255)
|
||||
.notNull.comment('Snapshot of the OAuth client name at call time, e.g. "Claude Code"'),
|
||||
column('status')
|
||||
.varchar(16)
|
||||
.notNull.withEnumCheck(['success', 'error', 'unfinished'])
|
||||
.comment(
|
||||
'Outcome of the tool call: success, error, or unfinished (the run outlived the call)',
|
||||
),
|
||||
column('durationMs').int.notNull.comment('Duration of the tool call in milliseconds'),
|
||||
// No foreign key to `execution_entity`: executions are pruned on a schedule and the table is busy.
|
||||
column('executionId')
|
||||
.varchar(36)
|
||||
.comment('Workflow execution ID when a workflow run started. NULL otherwise'),
|
||||
column('errorMessage').text.comment(
|
||||
'Safe error summary returned for a failed call. NULL on success',
|
||||
),
|
||||
column('startedAt')
|
||||
.timestampTimezone()
|
||||
.notNull.default('NOW()')
|
||||
.comment('When the tool call started'),
|
||||
)
|
||||
.withIndexOn(['serverId', 'startedAt', 'id'])
|
||||
// For a retention job that deletes calls by age, across all servers.
|
||||
.withIndexOn('startedAt')
|
||||
// The Logs tab sorts by these columns. `id` breaks ties, as in the queries.
|
||||
.withIndexOn(['serverId', 'durationMs', 'id'])
|
||||
.withIndexOn(['serverId', 'toolName', 'id'])
|
||||
.withIndexOn(['serverId', 'status', 'id'])
|
||||
.withIndexOn('toolId')
|
||||
.withIndexOn('userId')
|
||||
.withIndexOn('oauthClientId')
|
||||
.withForeignKey('serverId', {
|
||||
tableName: serverTable,
|
||||
columnName: 'id',
|
||||
onDelete: 'CASCADE',
|
||||
})
|
||||
.withForeignKey('toolId', {
|
||||
tableName: toolTable,
|
||||
columnName: 'id',
|
||||
onDelete: 'SET NULL',
|
||||
})
|
||||
.withForeignKey('userId', {
|
||||
tableName: 'user',
|
||||
columnName: 'id',
|
||||
onDelete: 'SET NULL',
|
||||
})
|
||||
.withForeignKey('oauthClientId', {
|
||||
tableName: 'oauth_clients',
|
||||
columnName: 'id',
|
||||
onDelete: 'SET NULL',
|
||||
});
|
||||
}
|
||||
|
||||
async down({ schemaBuilder: { dropTable } }: MigrationContext) {
|
||||
// Drops the tool call log table and removes all recorded MCP server tool call entries.
|
||||
await dropTable(toolCallTable);
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,12 @@ import {
|
||||
type OAuthDiscoveryClient,
|
||||
} from '@n8n/backend-services';
|
||||
import { createTeamProject, linkUserToProject } from '@n8n/backend-test-utils';
|
||||
import { NodeToolPort } from '@n8n/backend-module-mcp-servers';
|
||||
import {
|
||||
clearMcpServerTables,
|
||||
createMcpServer,
|
||||
createMcpServerTool,
|
||||
findMcpServerToolCalls,
|
||||
} from '@n8n/backend-module-mcp-servers/testing';
|
||||
import type { McpServerNodeTool } from '@n8n/api-types';
|
||||
import type { Project, User } from '@n8n/db';
|
||||
@@ -223,6 +225,18 @@ describe('Custom MCP server runtime with a node tool', () => {
|
||||
'mcp-server-tool-called',
|
||||
expect.objectContaining({ serverId, toolKind: 'node', status: 'success' }),
|
||||
);
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
toolName: 'greet_a_person',
|
||||
toolKind: 'node',
|
||||
targetId: null,
|
||||
userId: member.id,
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
executionId: null,
|
||||
errorMessage: null,
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
@@ -272,6 +286,52 @@ describe('Custom MCP server runtime with a node tool', () => {
|
||||
'mcp-server-tool-called',
|
||||
expect.objectContaining({ serverId, toolKind: 'node', status: 'error' }),
|
||||
);
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
toolName: 'call_greeting_service',
|
||||
toolKind: 'node',
|
||||
status: 'error',
|
||||
executionId: null,
|
||||
errorMessage: 'Error: The greeting service is down',
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it('logs a node run that outlives the wait as unfinished', async () => {
|
||||
await addNodeTool(
|
||||
'call_greeting_service',
|
||||
{
|
||||
name: 'Call the greeting service',
|
||||
nodeType: 'n8n-nodes-base.greetingService',
|
||||
nodeTypeVersion: 1,
|
||||
nodeParameters: {},
|
||||
},
|
||||
1,
|
||||
);
|
||||
vi.spyOn(Container.get(NodeToolPort), 'run').mockResolvedValue({
|
||||
status: 'running',
|
||||
finished: Promise.resolve(),
|
||||
});
|
||||
const emit = vi.spyOn(Container.get(EventService), 'emit');
|
||||
const client = await connect(member);
|
||||
|
||||
const result = await client.callTool({ name: 'call_greeting_service', arguments: {} });
|
||||
|
||||
expect(result.isError).toBe(true);
|
||||
expect(emit).toHaveBeenCalledWith(
|
||||
'mcp-server-tool-called',
|
||||
expect.objectContaining({ serverId, toolKind: 'node', status: 'error' }),
|
||||
);
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
toolName: 'call_greeting_service',
|
||||
toolKind: 'node',
|
||||
targetId: null,
|
||||
status: 'unfinished',
|
||||
executionId: null,
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
@@ -311,6 +371,24 @@ describe('Custom MCP server runtime with a node tool', () => {
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
toolName: 'removed_node',
|
||||
toolKind: 'node',
|
||||
status: 'error',
|
||||
errorMessage:
|
||||
'The node of this tool cannot run as a tool. Ask a builder of the server to fix it.',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
toolName: 'lost_credential',
|
||||
toolKind: 'node',
|
||||
status: 'error',
|
||||
errorMessage:
|
||||
'The credential of this tool is not available. Ask a builder of the server to fix it.',
|
||||
}),
|
||||
]),
|
||||
);
|
||||
await client.close();
|
||||
});
|
||||
});
|
||||
@@ -31,10 +31,13 @@ import {
|
||||
findMcpServer,
|
||||
findMcpServerConnection,
|
||||
findMcpServerConnections,
|
||||
findMcpServerToolCalls,
|
||||
findMcpServerTools,
|
||||
mcpServerToolCallRepository,
|
||||
softDeleteMcpServer,
|
||||
updateMcpServerConnectionLastUsedAt,
|
||||
} from '@n8n/backend-module-mcp-servers/testing';
|
||||
import type { Project, User } from '@n8n/db';
|
||||
import { User, type Project } from '@n8n/db';
|
||||
import { ProtectedResourceRegistry } from '@n8n/backend-services/auth';
|
||||
import { Container } from '@n8n/di';
|
||||
import { LocalAuthorizationServer } from '@n8n/inbound-auth';
|
||||
@@ -283,6 +286,19 @@ describe('Custom MCP server runtime with a real MCP client', () => {
|
||||
status: 'success',
|
||||
}),
|
||||
);
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
serverId,
|
||||
toolName: 'get_pipeline_summary',
|
||||
toolKind: 'workflow',
|
||||
userId: member.id,
|
||||
oauthClientId: CLIENT_ID,
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
executionId: '1',
|
||||
errorMessage: null,
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
@@ -309,6 +325,17 @@ describe('Custom MCP server runtime with a real MCP client', () => {
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
toolName: 'get_pipeline_summary',
|
||||
userId: member.id,
|
||||
status: 'error',
|
||||
executionId: '1',
|
||||
// Must store the safe generic error, never internal host/table details.
|
||||
errorMessage:
|
||||
'The workflow of this tool failed. A builder of the server can see the details in its executions.',
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
@@ -327,6 +354,14 @@ describe('Custom MCP server runtime with a real MCP client', () => {
|
||||
isError: true,
|
||||
content: [{ type: 'text', text: 'The campaign ID is unknown' }],
|
||||
});
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
toolName: 'get_pipeline_summary',
|
||||
status: 'error',
|
||||
executionId: '1',
|
||||
errorMessage: 'The campaign ID is unknown',
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
@@ -343,6 +378,38 @@ describe('Custom MCP server runtime with a real MCP client', () => {
|
||||
'mcp-server-tool-called',
|
||||
expect.objectContaining({ userId: member.id, status: 'error' }),
|
||||
);
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
toolName: 'get_pipeline_summary',
|
||||
status: 'error',
|
||||
executionId: null,
|
||||
errorMessage: 'The tool call failed. Check the server logs for details.',
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it('answers the tool call and sends the event when the log write fails', async () => {
|
||||
vi.spyOn(Container.get(WorkflowToolPort), 'run').mockResolvedValue({
|
||||
status: 'success',
|
||||
executionId: '1',
|
||||
finished: Promise.resolve(),
|
||||
output: [{ stage: 'Proposal', deals: 4 }],
|
||||
});
|
||||
vi.spyOn(mcpServerToolCallRepository(), 'insert').mockRejectedValue(new Error('db down'));
|
||||
const emit = vi.spyOn(Container.get(EventService), 'emit');
|
||||
const client = await connect(await tokenFor(member, resourceUrl(serverSlug)));
|
||||
|
||||
const result = await client.callTool({ name: 'get_pipeline_summary', arguments: {} });
|
||||
|
||||
expect(result).toEqual({
|
||||
content: [{ type: 'text', text: '[{"stage":"Proposal","deals":4}]' }],
|
||||
});
|
||||
expect(emit).toHaveBeenCalledWith(
|
||||
'mcp-server-tool-called',
|
||||
expect.objectContaining({ userId: member.id, status: 'success' }),
|
||||
);
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
@@ -355,6 +422,15 @@ describe('Custom MCP server runtime with a real MCP client', () => {
|
||||
isError: true,
|
||||
content: [{ type: 'text', text: expect.stringContaining('no longer exists') }],
|
||||
});
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
toolName: 'deleted_tool',
|
||||
toolKind: 'workflow',
|
||||
status: 'error',
|
||||
executionId: null,
|
||||
errorMessage: expect.stringContaining('no longer exists'),
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
@@ -408,16 +484,175 @@ describe('Custom MCP server runtime with a real MCP client', () => {
|
||||
expect(third.content).toEqual([
|
||||
{ type: 'text', text: expect.stringContaining('still running') },
|
||||
]);
|
||||
// Newest first: the run that outlived the wait is unfinished, the refused one is an error.
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({ status: 'unfinished', executionId: '1' }),
|
||||
expect.objectContaining({
|
||||
status: 'error',
|
||||
executionId: null,
|
||||
errorMessage: 'The server is busy. Try again in a moment.',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
status: 'unfinished',
|
||||
executionId: '1',
|
||||
errorMessage: expect.stringContaining('still running'),
|
||||
}),
|
||||
]);
|
||||
finish();
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it('still logs the call with toolId cleared when the tool is removed mid-run', async () => {
|
||||
const [tool] = await findMcpServerTools(serverId);
|
||||
vi.spyOn(Container.get(WorkflowToolPort), 'run').mockImplementation(async () => {
|
||||
await testServer
|
||||
.authAgentFor(member)
|
||||
.delete(`/projects/${project.id}/mcp-servers/${serverId}/tools/${tool.id}`)
|
||||
.expect(200);
|
||||
return {
|
||||
status: 'success',
|
||||
executionId: 'exec-mid-run',
|
||||
finished: Promise.resolve(),
|
||||
output: [{ ok: true }],
|
||||
};
|
||||
});
|
||||
const client = await connect(await tokenFor(member, resourceUrl(serverSlug)));
|
||||
|
||||
await client.callTool({ name: 'get_pipeline_summary', arguments: {} });
|
||||
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
serverId,
|
||||
toolId: null,
|
||||
toolName: 'get_pipeline_summary',
|
||||
userId: member.id,
|
||||
oauthClientId: CLIENT_ID,
|
||||
status: 'success',
|
||||
executionId: 'exec-mid-run',
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it('preserves toolId and userId when the OAuth client is removed mid-run', async () => {
|
||||
const [tool] = await findMcpServerTools(serverId);
|
||||
const tempClientId = `temp-client-${uuidv7().slice(-8)}`;
|
||||
const oauthClientRepo = Container.get(DataSource).getRepository(OAuthClient);
|
||||
await oauthClientRepo.save({
|
||||
id: tempClientId,
|
||||
name: 'Temporary client',
|
||||
redirectUris: ['https://example.com/callback'],
|
||||
grantTypes: ['authorization_code'],
|
||||
tokenEndpointAuthMethod: 'none',
|
||||
});
|
||||
vi.spyOn(Container.get(WorkflowToolPort), 'run').mockImplementation(async () => {
|
||||
await oauthClientRepo.delete({ id: tempClientId });
|
||||
return {
|
||||
status: 'success',
|
||||
executionId: 'exec-client-deleted',
|
||||
finished: Promise.resolve(),
|
||||
output: [{ ok: true }],
|
||||
};
|
||||
});
|
||||
const client = await connect(await tokenFor(member, resourceUrl(serverSlug), tempClientId));
|
||||
|
||||
await client.callTool({ name: 'get_pipeline_summary', arguments: {} });
|
||||
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
serverId,
|
||||
toolId: tool.id,
|
||||
toolName: 'get_pipeline_summary',
|
||||
userId: member.id,
|
||||
oauthClientId: null,
|
||||
clientName: 'Unknown client',
|
||||
status: 'success',
|
||||
executionId: 'exec-client-deleted',
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it('preserves userId when both the tool and OAuth client are removed mid-run', async () => {
|
||||
const [tool] = await findMcpServerTools(serverId);
|
||||
const tempClientId = `temp-client-${uuidv7().slice(-8)}`;
|
||||
const oauthClientRepo = Container.get(DataSource).getRepository(OAuthClient);
|
||||
await oauthClientRepo.save({
|
||||
id: tempClientId,
|
||||
name: 'Temporary client',
|
||||
redirectUris: ['https://example.com/callback'],
|
||||
grantTypes: ['authorization_code'],
|
||||
tokenEndpointAuthMethod: 'none',
|
||||
});
|
||||
vi.spyOn(Container.get(WorkflowToolPort), 'run').mockImplementation(async () => {
|
||||
await testServer
|
||||
.authAgentFor(member)
|
||||
.delete(`/projects/${project.id}/mcp-servers/${serverId}/tools/${tool.id}`)
|
||||
.expect(200);
|
||||
await oauthClientRepo.delete({ id: tempClientId });
|
||||
return {
|
||||
status: 'success',
|
||||
executionId: 'exec-tool-and-client-deleted',
|
||||
finished: Promise.resolve(),
|
||||
output: [{ ok: true }],
|
||||
};
|
||||
});
|
||||
const client = await connect(await tokenFor(member, resourceUrl(serverSlug), tempClientId));
|
||||
|
||||
await client.callTool({ name: 'get_pipeline_summary', arguments: {} });
|
||||
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
serverId,
|
||||
toolId: null,
|
||||
toolName: 'get_pipeline_summary',
|
||||
userId: member.id,
|
||||
oauthClientId: null,
|
||||
status: 'success',
|
||||
executionId: 'exec-tool-and-client-deleted',
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it('preserves toolId and oauthClientId when the user is removed mid-run', async () => {
|
||||
const [tool] = await findMcpServerTools(serverId);
|
||||
const tempUser = await createMember();
|
||||
await linkUserToProject(tempUser, project, 'project:editor');
|
||||
vi.spyOn(Container.get(WorkflowToolPort), 'run').mockImplementation(async () => {
|
||||
await Container.get(DataSource).getRepository(User).delete({ id: tempUser.id });
|
||||
return {
|
||||
status: 'success',
|
||||
executionId: 'exec-user-deleted',
|
||||
finished: Promise.resolve(),
|
||||
output: [{ ok: true }],
|
||||
};
|
||||
});
|
||||
const client = await connect(await tokenFor(tempUser, resourceUrl(serverSlug)));
|
||||
|
||||
await client.callTool({ name: 'get_pipeline_summary', arguments: {} });
|
||||
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
serverId,
|
||||
toolId: tool.id,
|
||||
toolName: 'get_pipeline_summary',
|
||||
userId: null,
|
||||
oauthClientId: CLIENT_ID,
|
||||
status: 'success',
|
||||
executionId: 'exec-user-deleted',
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it('answers an unknown tool with a JSON-RPC error', async () => {
|
||||
const client = await connect(await tokenFor(member, resourceUrl(serverSlug)));
|
||||
|
||||
await expect(client.callTool({ name: 'no_such_tool', arguments: {} })).rejects.toThrow(
|
||||
/Unknown tool: no_such_tool/,
|
||||
);
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([]);
|
||||
await client.close();
|
||||
});
|
||||
});
|
||||
@@ -495,6 +730,17 @@ describe('Custom MCP server runtime with an agent tool', () => {
|
||||
'mcp-server-tool-called',
|
||||
expect.objectContaining({ userId: viewer.id, toolKind: 'agent', status: 'success' }),
|
||||
);
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
toolName: 'write_copy',
|
||||
toolKind: 'agent',
|
||||
targetId: AGENT_ID,
|
||||
userId: viewer.id,
|
||||
status: 'success',
|
||||
executionId: null,
|
||||
errorMessage: null,
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
@@ -559,6 +805,14 @@ describe('Custom MCP server runtime with an agent tool', () => {
|
||||
/Send a "message"/,
|
||||
);
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
toolName: 'write_copy',
|
||||
toolKind: 'agent',
|
||||
status: 'error',
|
||||
errorMessage: expect.stringContaining('Send a "message"'),
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
@@ -577,6 +831,14 @@ describe('Custom MCP server runtime with an agent tool', () => {
|
||||
isError: true,
|
||||
content: [{ type: 'text', text: expect.stringContaining(text) }],
|
||||
});
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
toolKind: 'agent',
|
||||
status: 'error',
|
||||
executionId: null,
|
||||
errorMessage: expect.stringContaining(text),
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
@@ -600,6 +862,16 @@ describe('Custom MCP server runtime with an agent tool', () => {
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(await findMcpServerToolCalls(serverId)).toEqual([
|
||||
expect.objectContaining({
|
||||
toolName: 'write_copy',
|
||||
toolKind: 'agent',
|
||||
status: 'error',
|
||||
executionId: null,
|
||||
errorMessage:
|
||||
'The agent of this tool failed. A builder of the server can see the details in the sessions of the agent.',
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
@@ -634,6 +906,11 @@ describe('Custom MCP server runtime with an agent tool', () => {
|
||||
expect(third.content).toEqual([
|
||||
{ type: 'text', text: expect.stringContaining('still working') },
|
||||
]);
|
||||
expect((await findMcpServerToolCalls(serverId)).map((call) => call.status)).toEqual([
|
||||
'unfinished',
|
||||
'error',
|
||||
'unfinished',
|
||||
]);
|
||||
await client.close();
|
||||
});
|
||||
});
|
||||
@@ -711,6 +988,14 @@ describe('Custom MCP server runtime with input settings', () => {
|
||||
'mcp-server-tool-called',
|
||||
expect.objectContaining({ userId: member.id, status: 'error' }),
|
||||
);
|
||||
expect(await findMcpServerToolCalls()).toEqual([
|
||||
expect.objectContaining({
|
||||
toolName: 'get_owner_pipeline',
|
||||
status: 'error',
|
||||
executionId: null,
|
||||
errorMessage: 'The required input "owner_email" is missing. Send a value for it.',
|
||||
}),
|
||||
]);
|
||||
await client.close();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
import { CUSTOM_MCP_SERVERS_FLAG, CUSTOM_MCP_SERVERS_FLAG_VARIANT } from '@n8n/api-types';
|
||||
import { PostHogClient } from '@n8n/backend-services';
|
||||
import { createTeamProject, linkUserToProject } from '@n8n/backend-test-utils';
|
||||
import {
|
||||
clearMcpServerTables,
|
||||
createMcpServerTool,
|
||||
createMcpServerToolCall,
|
||||
} from '@n8n/backend-module-mcp-servers/testing';
|
||||
import { GLOBAL_MEMBER_ROLE, type Project, type User } from '@n8n/db';
|
||||
import { Container } from '@n8n/di';
|
||||
import type { AssignableProjectRole } from '@n8n/permissions';
|
||||
import { DataSource } from '@n8n/typeorm';
|
||||
|
||||
import { OAuthClient } from '@/modules/oauth-server/database/entities/oauth-client.entity';
|
||||
|
||||
import { createMember, createOwner, createUser } from '../shared/db/users';
|
||||
import type { SuperAgentTest } from '../shared/types';
|
||||
import * as utils from '../shared/utils/';
|
||||
|
||||
const testServer = utils.setupTestServer({
|
||||
endpointGroups: ['mcp-servers'],
|
||||
modules: ['inbound-auth-core', 'oauth-jwe', 'oauth-server', 'mcp-servers'],
|
||||
});
|
||||
|
||||
const CLAUDE_CODE = 'claude-code-client';
|
||||
const CURSOR = 'cursor-client';
|
||||
|
||||
const ROLES: AssignableProjectRole[] = [
|
||||
'project:admin',
|
||||
'project:editor',
|
||||
'project:viewer',
|
||||
'project:chatUser',
|
||||
];
|
||||
|
||||
let owner: User;
|
||||
let outsider: User;
|
||||
let maya: User;
|
||||
let tom: User;
|
||||
let project: Project;
|
||||
const roleUsers = {} as Record<AssignableProjectRole, User>;
|
||||
let ownerAgent: SuperAgentTest;
|
||||
let server: { id: string; slug: string };
|
||||
|
||||
const agentFor = (role: AssignableProjectRole) => testServer.authAgentFor(roleUsers[role]);
|
||||
const serverPath = (serverId = server.id, projectId = project.id) =>
|
||||
`/projects/${projectId}/mcp-servers/${serverId}`;
|
||||
|
||||
function setFlag(on: boolean) {
|
||||
vi.mocked(Container.get(PostHogClient).getFeatureFlagForInstance).mockImplementation(
|
||||
async (flag) =>
|
||||
on && flag === CUSTOM_MCP_SERVERS_FLAG ? CUSTOM_MCP_SERVERS_FLAG_VARIANT : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
async function createServer(slug: string, projectId = project.id) {
|
||||
const response = await ownerAgent
|
||||
.post(`/projects/${projectId}/mcp-servers`)
|
||||
.send({ name: 'Support desk', slug })
|
||||
.expect(200);
|
||||
return response.body.data as { id: string; slug: string };
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
owner = await createOwner();
|
||||
outsider = await createMember();
|
||||
maya = await createUser({
|
||||
role: GLOBAL_MEMBER_ROLE,
|
||||
firstName: 'Maya',
|
||||
lastName: 'Fischer',
|
||||
email: 'maya@acme.com',
|
||||
});
|
||||
tom = await createUser({
|
||||
role: GLOBAL_MEMBER_ROLE,
|
||||
firstName: 'Tom',
|
||||
lastName: 'Becker',
|
||||
email: 'tom@acme.com',
|
||||
});
|
||||
project = await createTeamProject('Support', owner);
|
||||
for (const role of ROLES) {
|
||||
roleUsers[role] = await createMember();
|
||||
await linkUserToProject(roleUsers[role], project, role);
|
||||
}
|
||||
await linkUserToProject(maya, project, 'project:viewer');
|
||||
await linkUserToProject(tom, project, 'project:viewer');
|
||||
ownerAgent = testServer.authAgentFor(owner);
|
||||
|
||||
const clients = Container.get(DataSource).getRepository(OAuthClient);
|
||||
for (const [id, name] of [
|
||||
[CLAUDE_CODE, 'Claude Code'],
|
||||
[CURSOR, 'Cursor'],
|
||||
]) {
|
||||
await clients.save({
|
||||
id,
|
||||
name,
|
||||
redirectUris: ['https://example.com/callback'],
|
||||
grantTypes: ['authorization_code'],
|
||||
tokenEndpointAuthMethod: 'none',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await clearMcpServerTables();
|
||||
setFlag(true);
|
||||
server = await createServer('support-desk');
|
||||
});
|
||||
|
||||
describe('GET /projects/:projectId/mcp-servers/:serverId/tool-calls', () => {
|
||||
it('lists tool calls newest first with resolved callers, execution info, and filter options', async () => {
|
||||
const tool = await createMcpServerTool({
|
||||
serverId: server.id,
|
||||
toolName: 'create_ticket',
|
||||
targetId: 'wf-2',
|
||||
});
|
||||
await createMcpServerToolCall({
|
||||
serverId: server.id,
|
||||
toolId: tool.id,
|
||||
toolName: 'create_ticket',
|
||||
toolKind: 'workflow',
|
||||
targetId: 'wf-2',
|
||||
userId: maya.id,
|
||||
oauthClientId: CLAUDE_CODE,
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 180,
|
||||
executionId: 'exec-10',
|
||||
startedAt: new Date('2026-11-24T10:00:00.000Z'),
|
||||
});
|
||||
await createMcpServerToolCall({
|
||||
serverId: server.id,
|
||||
toolId: null,
|
||||
toolName: 'deleted_tool',
|
||||
toolKind: 'workflow',
|
||||
targetId: 'wf-old',
|
||||
userId: tom.id,
|
||||
oauthClientId: CURSOR,
|
||||
clientName: 'Cursor',
|
||||
status: 'error',
|
||||
durationMs: 45,
|
||||
executionId: null,
|
||||
errorMessage: 'The workflow of this tool no longer exists.',
|
||||
startedAt: new Date('2026-11-25T12:00:00.000Z'),
|
||||
});
|
||||
await createMcpServerTool({
|
||||
serverId: server.id,
|
||||
toolName: 'uncalled_tool',
|
||||
targetId: 'wf-3',
|
||||
});
|
||||
|
||||
const response = await agentFor('project:viewer').get(`${serverPath()}/tool-calls`).expect(200);
|
||||
|
||||
expect(response.body.data).toEqual({
|
||||
total: 2,
|
||||
items: [
|
||||
{
|
||||
id: expect.any(Number),
|
||||
toolId: null,
|
||||
toolName: 'deleted_tool',
|
||||
toolKind: 'workflow',
|
||||
targetId: 'wf-old',
|
||||
caller: {
|
||||
userId: tom.id,
|
||||
firstName: 'Tom',
|
||||
lastName: 'Becker',
|
||||
email: 'tom@acme.com',
|
||||
},
|
||||
clientName: 'Cursor',
|
||||
status: 'error',
|
||||
durationMs: 45,
|
||||
executionId: null,
|
||||
errorMessage: 'The workflow of this tool no longer exists.',
|
||||
startedAt: '2026-11-25T12:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: expect.any(Number),
|
||||
toolId: tool.id,
|
||||
toolName: 'create_ticket',
|
||||
toolKind: 'workflow',
|
||||
targetId: 'wf-2',
|
||||
caller: {
|
||||
userId: maya.id,
|
||||
firstName: 'Maya',
|
||||
lastName: 'Fischer',
|
||||
email: 'maya@acme.com',
|
||||
},
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 180,
|
||||
executionId: 'exec-10',
|
||||
errorMessage: null,
|
||||
startedAt: '2026-11-24T10:00:00.000Z',
|
||||
},
|
||||
],
|
||||
filters: {
|
||||
tools: ['create_ticket', 'deleted_tool', 'uncalled_tool'],
|
||||
callers: [
|
||||
{ userId: maya.id, firstName: 'Maya', lastName: 'Fischer', email: 'maya@acme.com' },
|
||||
{ userId: tom.id, firstName: 'Tom', lastName: 'Becker', email: 'tom@acme.com' },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('filters by toolName, userId, status, and date range', async () => {
|
||||
await createMcpServerToolCall({
|
||||
serverId: server.id,
|
||||
toolName: 'get_pipeline',
|
||||
userId: maya.id,
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 100,
|
||||
startedAt: new Date('2026-11-20T09:00:00.000Z'),
|
||||
});
|
||||
await createMcpServerToolCall({
|
||||
serverId: server.id,
|
||||
toolName: 'create_ticket',
|
||||
userId: maya.id,
|
||||
clientName: 'Claude Code',
|
||||
status: 'error',
|
||||
durationMs: 250,
|
||||
errorMessage: 'Failed',
|
||||
startedAt: new Date('2026-11-22T09:00:00.000Z'),
|
||||
});
|
||||
await createMcpServerToolCall({
|
||||
serverId: server.id,
|
||||
toolName: 'get_pipeline',
|
||||
userId: tom.id,
|
||||
clientName: 'Cursor',
|
||||
status: 'error',
|
||||
durationMs: 400,
|
||||
errorMessage: 'Busy',
|
||||
startedAt: new Date('2026-11-24T09:00:00.000Z'),
|
||||
});
|
||||
|
||||
const byTool = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({ toolName: 'get_pipeline' })
|
||||
.expect(200);
|
||||
expect(byTool.body.data.total).toBe(2);
|
||||
expect(byTool.body.data.items.map((item: { toolName: string }) => item.toolName)).toEqual([
|
||||
'get_pipeline',
|
||||
'get_pipeline',
|
||||
]);
|
||||
|
||||
const byUser = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({ userId: tom.id })
|
||||
.expect(200);
|
||||
expect(byUser.body.data.total).toBe(1);
|
||||
expect(byUser.body.data.items[0].caller.userId).toBe(tom.id);
|
||||
|
||||
const byStatus = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({ status: 'error' })
|
||||
.expect(200);
|
||||
expect(byStatus.body.data.total).toBe(2);
|
||||
|
||||
const byDateRange = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({
|
||||
startedAfter: '2026-11-21T00:00:00.000Z',
|
||||
startedBefore: '2026-11-23T00:00:00.000Z',
|
||||
})
|
||||
.expect(200);
|
||||
expect(byDateRange.body.data.total).toBe(1);
|
||||
expect(byDateRange.body.data.items[0].toolName).toBe('create_ticket');
|
||||
});
|
||||
|
||||
it('sorts by startedAt, durationMs, toolName, and status, and paginates results', async () => {
|
||||
await createMcpServerToolCall({
|
||||
serverId: server.id,
|
||||
toolName: 'zeta_tool',
|
||||
userId: maya.id,
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 300,
|
||||
startedAt: new Date('2026-11-24T10:00:00.000Z'),
|
||||
});
|
||||
await createMcpServerToolCall({
|
||||
serverId: server.id,
|
||||
toolName: 'alpha_tool',
|
||||
userId: maya.id,
|
||||
clientName: 'Claude Code',
|
||||
status: 'error',
|
||||
durationMs: 50,
|
||||
startedAt: new Date('2026-11-24T11:00:00.000Z'),
|
||||
});
|
||||
await createMcpServerToolCall({
|
||||
serverId: server.id,
|
||||
toolName: 'mid_tool',
|
||||
userId: maya.id,
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 150,
|
||||
startedAt: new Date('2026-11-24T12:00:00.000Z'),
|
||||
});
|
||||
|
||||
const byDurationDesc = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({ sortBy: 'durationMs', sortDirection: 'desc' })
|
||||
.expect(200);
|
||||
expect(
|
||||
byDurationDesc.body.data.items.map((item: { durationMs: number }) => item.durationMs),
|
||||
).toEqual([300, 150, 50]);
|
||||
|
||||
const byToolAsc = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({ sortBy: 'toolName', sortDirection: 'asc' })
|
||||
.expect(200);
|
||||
expect(byToolAsc.body.data.items.map((item: { toolName: string }) => item.toolName)).toEqual([
|
||||
'alpha_tool',
|
||||
'mid_tool',
|
||||
'zeta_tool',
|
||||
]);
|
||||
|
||||
const page2 = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({ sortBy: 'startedAt', sortDirection: 'desc', limit: 2, offset: 2 })
|
||||
.expect(200);
|
||||
expect(page2.body.data.total).toBe(3);
|
||||
expect(page2.body.data.items.map((item: { toolName: string }) => item.toolName)).toEqual([
|
||||
'zeta_tool',
|
||||
]);
|
||||
});
|
||||
|
||||
it('pages through calls with the same sort value without a repeat or a gap', async () => {
|
||||
for (const toolName of ['tool_a', 'tool_b', 'tool_c']) {
|
||||
await createMcpServerToolCall({
|
||||
serverId: server.id,
|
||||
toolName,
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 100,
|
||||
startedAt: new Date('2026-11-24T10:00:00.000Z'),
|
||||
});
|
||||
}
|
||||
|
||||
const seen: string[] = [];
|
||||
for (const offset of [0, 1, 2]) {
|
||||
const page = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({ sortBy: 'durationMs', sortDirection: 'asc', limit: 1, offset })
|
||||
.expect(200);
|
||||
expect(page.body.data.total).toBe(3);
|
||||
seen.push(...page.body.data.items.map((item: { toolName: string }) => item.toolName));
|
||||
}
|
||||
|
||||
expect(seen.toSorted()).toEqual(['tool_a', 'tool_b', 'tool_c']);
|
||||
});
|
||||
|
||||
it('sorts by status, and keeps calls exactly on a date bound', async () => {
|
||||
const bounds = { after: '2026-11-20T09:00:00.000Z', before: '2026-11-22T09:00:00.000Z' };
|
||||
for (const [toolName, status, startedAt] of [
|
||||
['on_start', 'success', bounds.after],
|
||||
['inside', 'unfinished', '2026-11-21T09:00:00.000Z'],
|
||||
['on_end', 'error', bounds.before],
|
||||
['outside', 'success', '2026-11-22T09:00:00.001Z'],
|
||||
] as const) {
|
||||
await createMcpServerToolCall({
|
||||
serverId: server.id,
|
||||
toolName,
|
||||
clientName: 'Claude Code',
|
||||
status,
|
||||
durationMs: 100,
|
||||
startedAt: new Date(startedAt),
|
||||
});
|
||||
}
|
||||
|
||||
const response = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({
|
||||
startedAfter: bounds.after,
|
||||
startedBefore: bounds.before,
|
||||
sortBy: 'status',
|
||||
sortDirection: 'asc',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.data.total).toBe(3);
|
||||
// Errors first, then unfinished runs, then successes, as the sort labels say.
|
||||
expect(
|
||||
response.body.data.items.map((item: { toolName: string; status: string }) => item.status),
|
||||
).toEqual(['error', 'unfinished', 'success']);
|
||||
|
||||
const succeededFirst = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({
|
||||
startedAfter: bounds.after,
|
||||
startedBefore: bounds.before,
|
||||
sortBy: 'status',
|
||||
sortDirection: 'desc',
|
||||
})
|
||||
.expect(200);
|
||||
expect(succeededFirst.body.data.items.map((item: { status: string }) => item.status)).toEqual([
|
||||
'success',
|
||||
'unfinished',
|
||||
'error',
|
||||
]);
|
||||
|
||||
// A page that starts inside one status group and ends in the next.
|
||||
const acrossGroups = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({
|
||||
startedAfter: bounds.after,
|
||||
startedBefore: bounds.before,
|
||||
sortBy: 'status',
|
||||
sortDirection: 'asc',
|
||||
limit: 2,
|
||||
offset: 1,
|
||||
})
|
||||
.expect(200);
|
||||
expect(acrossGroups.body.data.items.map((item: { status: string }) => item.status)).toEqual([
|
||||
'unfinished',
|
||||
'success',
|
||||
]);
|
||||
|
||||
const oneStatus = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({ status: 'success', sortBy: 'status', sortDirection: 'asc' })
|
||||
.expect(200);
|
||||
expect(oneStatus.body.data.items.map((item: { toolName: string }) => item.toolName)).toEqual([
|
||||
'on_start',
|
||||
'outside',
|
||||
]);
|
||||
});
|
||||
|
||||
it('answers an offset past the end with no items and the full total', async () => {
|
||||
await createMcpServerToolCall({
|
||||
serverId: server.id,
|
||||
toolName: 'get_pipeline',
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 100,
|
||||
});
|
||||
|
||||
const response = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({ offset: 50 })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.data).toEqual(expect.objectContaining({ items: [], total: 1 }));
|
||||
|
||||
const atCap = await ownerAgent
|
||||
.get(`${serverPath()}/tool-calls`)
|
||||
.query({ offset: 10_000 })
|
||||
.expect(200);
|
||||
expect(atCap.body.data.items).toEqual([]);
|
||||
});
|
||||
|
||||
it('isolates tool calls to the requested server and project', async () => {
|
||||
const other = await createServer('other-desk');
|
||||
await createMcpServerToolCall({
|
||||
serverId: other.id,
|
||||
toolName: 'other_tool',
|
||||
userId: maya.id,
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 90,
|
||||
});
|
||||
|
||||
const response = await ownerAgent.get(`${serverPath()}/tool-calls`).expect(200);
|
||||
|
||||
expect(response.body.data).toEqual({
|
||||
items: [],
|
||||
total: 0,
|
||||
filters: { tools: [], callers: [] },
|
||||
});
|
||||
|
||||
const otherProject = await createTeamProject('Billing', owner);
|
||||
const elsewhere = await createServer('billing-desk', otherProject.id);
|
||||
await ownerAgent.get(`${serverPath(elsewhere.id)}/tool-calls`).expect(404);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['project:admin', 200],
|
||||
['project:editor', 200],
|
||||
['project:viewer', 200],
|
||||
['project:chatUser', 403],
|
||||
] as const)('answers %s with %i', async (role, status) => {
|
||||
await agentFor(role).get(`${serverPath()}/tool-calls`).expect(status);
|
||||
});
|
||||
|
||||
it('refuses a person outside the project', async () => {
|
||||
await testServer.authAgentFor(outsider).get(`${serverPath()}/tool-calls`).expect(403);
|
||||
});
|
||||
|
||||
it('answers 404 for an unknown, non-UUID, or deleted server, and when the flag is off', async () => {
|
||||
await ownerAgent
|
||||
.get(`${serverPath('0195b6e0-0000-7000-8000-000000000000')}/tool-calls`)
|
||||
.expect(404);
|
||||
await ownerAgent.get(`${serverPath('not-a-uuid')}/tool-calls`).expect(404);
|
||||
|
||||
const deleted = await createServer('old-desk');
|
||||
await ownerAgent.delete(serverPath(deleted.id)).expect(200);
|
||||
await ownerAgent.get(`${serverPath(deleted.id)}/tool-calls`).expect(404);
|
||||
|
||||
setFlag(false);
|
||||
await ownerAgent.get(`${serverPath()}/tool-calls`).expect(404);
|
||||
});
|
||||
|
||||
it('rejects invalid query parameters with 400', async () => {
|
||||
await ownerAgent.get(`${serverPath()}/tool-calls`).query({ status: 'running' }).expect(400);
|
||||
await ownerAgent.get(`${serverPath()}/tool-calls`).query({ limit: 500 }).expect(400);
|
||||
await ownerAgent.get(`${serverPath()}/tool-calls`).query({ offset: 10_001 }).expect(400);
|
||||
await ownerAgent.get(`${serverPath()}/tool-calls`).query({ userId: 'bad' }).expect(400);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import {
|
||||
createTestMigrationContext,
|
||||
initDbUpToMigration,
|
||||
runSingleMigration,
|
||||
undoLastSingleMigration,
|
||||
type TestMigrationContext,
|
||||
} from '@n8n/backend-test-utils';
|
||||
import { DbConnection } from '@n8n/db';
|
||||
import { Container } from '@n8n/di';
|
||||
import { DataSource } from '@n8n/typeorm';
|
||||
import { v7 as uuidv7 } from 'uuid';
|
||||
|
||||
const migrationName = 'CreateMcpServerToolCallTable1796327881234';
|
||||
const tableName = 'mcp_server_tool_call';
|
||||
|
||||
describe('CreateMcpServerToolCallTable migration', () => {
|
||||
let dataSource: DataSource;
|
||||
let context: TestMigrationContext;
|
||||
|
||||
beforeAll(async () => {
|
||||
await Container.get(DbConnection).init();
|
||||
dataSource = Container.get(DataSource);
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
context = createTestMigrationContext(dataSource);
|
||||
await context.queryRunner.clearDatabase();
|
||||
await context.queryRunner.release();
|
||||
await initDbUpToMigration(migrationName);
|
||||
await runSingleMigration(migrationName);
|
||||
context = createTestMigrationContext(dataSource);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (!context.queryRunner.isReleased) await context.queryRunner.release();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await Container.get(DbConnection).close();
|
||||
});
|
||||
|
||||
async function insert(table: string, row: Record<string, unknown>) {
|
||||
const { escape, runQuery } = context;
|
||||
const columns = Object.keys(row);
|
||||
await runQuery(
|
||||
`INSERT INTO ${escape.tableName(table)} (${columns.map(escape.columnName).join(', ')})
|
||||
VALUES (${columns.map((column) => `:${column}`).join(', ')})`,
|
||||
row,
|
||||
);
|
||||
}
|
||||
|
||||
async function count(table: string) {
|
||||
const { escape, runQuery } = context;
|
||||
const [row] = await runQuery<Array<{ count: number | string }>>(
|
||||
`SELECT COUNT(*) AS ${escape.columnName('count')} FROM ${escape.tableName(table)}`,
|
||||
);
|
||||
return Number(row.count);
|
||||
}
|
||||
|
||||
async function seedPrerequisites() {
|
||||
const projectId = uuidv7();
|
||||
await insert('project', { id: projectId, name: 'Test project', type: 'team' });
|
||||
|
||||
const userId = uuidv7();
|
||||
await insert('user', {
|
||||
id: userId,
|
||||
email: `${userId}@example.com`,
|
||||
firstName: 'Test',
|
||||
lastName: 'User',
|
||||
password: 'password',
|
||||
roleSlug: 'global:member',
|
||||
});
|
||||
|
||||
const clientId = uuidv7();
|
||||
await insert('oauth_clients', {
|
||||
id: clientId,
|
||||
name: 'Claude Code',
|
||||
redirectUris: '[]',
|
||||
grantTypes: '[]',
|
||||
});
|
||||
|
||||
const serverId = uuidv7();
|
||||
await insert('mcp_server', {
|
||||
id: serverId,
|
||||
projectId,
|
||||
name: 'Sales tools',
|
||||
slug: `sales-tools-${serverId.slice(-8)}`,
|
||||
});
|
||||
|
||||
const toolId = uuidv7();
|
||||
await insert('mcp_server_tool', {
|
||||
id: toolId,
|
||||
serverId,
|
||||
kind: 'workflow',
|
||||
targetId: 'wf-1',
|
||||
toolName: 'get_pipeline',
|
||||
});
|
||||
|
||||
return { projectId, userId, clientId, serverId, toolId };
|
||||
}
|
||||
|
||||
async function insertToolCall(serverId: string, overrides: Record<string, unknown> = {}) {
|
||||
await insert(tableName, {
|
||||
serverId,
|
||||
toolName: 'get_pipeline',
|
||||
toolKind: 'workflow',
|
||||
targetId: 'wf-1',
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 120,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
it('generates an integer id and sets startedAt by default', async () => {
|
||||
const { serverId, toolId, userId, clientId } = await seedPrerequisites();
|
||||
await insertToolCall(serverId, { toolId, userId, oauthClientId: clientId });
|
||||
const { escape, runQuery } = context;
|
||||
|
||||
const [row] = await runQuery<Array<{ id: number; startedAt: Date | string }>>(
|
||||
`SELECT ${['id', 'startedAt'].map(escape.columnName).join(', ')}
|
||||
FROM ${escape.tableName(tableName)}`,
|
||||
);
|
||||
|
||||
expect(Number(row.id)).toBeGreaterThan(0);
|
||||
expect(row.startedAt).toBeTruthy();
|
||||
});
|
||||
|
||||
it('accepts only the allowed tool kinds and statuses', async () => {
|
||||
const { serverId } = await seedPrerequisites();
|
||||
|
||||
await insertToolCall(serverId, { toolKind: 'workflow', status: 'success' });
|
||||
await insertToolCall(serverId, { toolKind: 'node', targetId: null, status: 'error' });
|
||||
await insertToolCall(serverId, { toolKind: 'agent', status: 'success' });
|
||||
await insertToolCall(serverId, { toolKind: 'skill', status: 'error' });
|
||||
await insertToolCall(serverId, { toolKind: 'workflow', status: 'unfinished' });
|
||||
|
||||
await expect(insertToolCall(serverId, { toolKind: 'webhook' })).rejects.toThrow();
|
||||
await expect(insertToolCall(serverId, { status: 'running' })).rejects.toThrow();
|
||||
expect(await count(tableName)).toBe(5);
|
||||
});
|
||||
|
||||
it('deletes tool call rows when the server is deleted', async () => {
|
||||
const { serverId, toolId, userId, clientId } = await seedPrerequisites();
|
||||
await insertToolCall(serverId, { toolId, userId, oauthClientId: clientId });
|
||||
const { escape, runQuery } = context;
|
||||
|
||||
await runQuery(
|
||||
`DELETE FROM ${escape.tableName('mcp_server')} WHERE ${escape.columnName('id')} = :id`,
|
||||
{ id: serverId },
|
||||
);
|
||||
|
||||
expect(await count(tableName)).toBe(0);
|
||||
});
|
||||
|
||||
it('keeps the log row and clears toolId, userId, and oauthClientId when those records are deleted', async () => {
|
||||
const { serverId, toolId, userId, clientId } = await seedPrerequisites();
|
||||
await insertToolCall(serverId, {
|
||||
toolId,
|
||||
userId,
|
||||
oauthClientId: clientId,
|
||||
clientName: 'Claude Code',
|
||||
toolName: 'get_pipeline',
|
||||
});
|
||||
const { escape, runQuery } = context;
|
||||
|
||||
await runQuery(
|
||||
`DELETE FROM ${escape.tableName('mcp_server_tool')} WHERE ${escape.columnName('id')} = :id`,
|
||||
{ id: toolId },
|
||||
);
|
||||
await runQuery(
|
||||
`DELETE FROM ${escape.tableName('user')} WHERE ${escape.columnName('id')} = :id`,
|
||||
{ id: userId },
|
||||
);
|
||||
await runQuery(
|
||||
`DELETE FROM ${escape.tableName('oauth_clients')} WHERE ${escape.columnName('id')} = :id`,
|
||||
{ id: clientId },
|
||||
);
|
||||
|
||||
const [row] = await runQuery<
|
||||
Array<{
|
||||
toolId: string | null;
|
||||
userId: string | null;
|
||||
oauthClientId: string | null;
|
||||
toolName: string;
|
||||
clientName: string;
|
||||
}>
|
||||
>(
|
||||
`SELECT ${['toolId', 'userId', 'oauthClientId', 'toolName', 'clientName']
|
||||
.map(escape.columnName)
|
||||
.join(', ')}
|
||||
FROM ${escape.tableName(tableName)}`,
|
||||
);
|
||||
|
||||
expect(row).toEqual({
|
||||
toolId: null,
|
||||
userId: null,
|
||||
oauthClientId: null,
|
||||
toolName: 'get_pipeline',
|
||||
clientName: 'Claude Code',
|
||||
});
|
||||
});
|
||||
|
||||
it('reverts a populated table and can run again', async () => {
|
||||
const { serverId, toolId, userId, clientId } = await seedPrerequisites();
|
||||
await insertToolCall(serverId, { toolId, userId, oauthClientId: clientId });
|
||||
await context.queryRunner.release();
|
||||
|
||||
await undoLastSingleMigration();
|
||||
context = createTestMigrationContext(dataSource);
|
||||
expect(await context.queryRunner.hasTable(`${context.tablePrefix}${tableName}`)).toBe(false);
|
||||
await context.queryRunner.release();
|
||||
|
||||
await runSingleMigration(migrationName);
|
||||
context = createTestMigrationContext(dataSource);
|
||||
expect(await context.queryRunner.hasTable(`${context.tablePrefix}${tableName}`)).toBe(true);
|
||||
await insertToolCall(serverId);
|
||||
expect(await count(tableName)).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -2610,6 +2610,7 @@
|
||||
"mcpServers.empty.description": "Share one server with your team and their AI clients, with only the tools you choose.",
|
||||
"mcpServers.server.tabs.contents": "Build",
|
||||
"mcpServers.server.tabs.connections": "Access",
|
||||
"mcpServers.server.tabs.logs": "Logs",
|
||||
"mcpServers.list.error": "Could not load the MCP servers",
|
||||
"mcpServers.list.search": "Search MCP servers",
|
||||
"mcpServers.list.noResults": "No MCP servers match your search",
|
||||
@@ -2890,6 +2891,46 @@
|
||||
"mcpServers.connections.remove.description.personalProject": "This ends the block of {name}. {name} can connect again. | This deletes the connection of {name} from this list and ends the block. {name} can connect again. | This deletes the {count} connections of {name} from this list and ends the block. {name} can connect again.",
|
||||
"mcpServers.connections.remove.success": "{name} removed",
|
||||
"mcpServers.connections.remove.error": "Could not remove {name}",
|
||||
"mcpServers.logs.load.error": "Could not load the tool call log",
|
||||
"mcpServers.logs.load.retry": "Try again",
|
||||
"mcpServers.logs.refresh": "Refresh",
|
||||
"mcpServers.logs.autoRefresh": "Auto refresh",
|
||||
"mcpServers.logs.empty.heading": "No tool calls yet",
|
||||
"mcpServers.logs.empty.description": "When AI clients call tools on this server, each call shows up here.",
|
||||
"mcpServers.logs.empty.filtered.heading": "No tool calls match your filters",
|
||||
"mcpServers.logs.empty.filtered.description": "Adjust or reset your filters to see other tool calls.",
|
||||
"mcpServers.logs.column.tool": "Tool",
|
||||
"mcpServers.logs.column.person": "Person",
|
||||
"mcpServers.logs.column.client": "Client",
|
||||
"mcpServers.logs.column.status": "Status",
|
||||
"mcpServers.logs.column.startedAt": "Started",
|
||||
"mcpServers.logs.column.duration": "Run time",
|
||||
"mcpServers.logs.column.execution": "Execution",
|
||||
"mcpServers.logs.status.success": "Succeeded",
|
||||
"mcpServers.logs.status.error": "Error",
|
||||
"mcpServers.logs.status.unfinished": "Unfinished",
|
||||
"mcpServers.logs.viewExecution": "View execution",
|
||||
"mcpServers.logs.filter.button": "Filters",
|
||||
"mcpServers.logs.filter.tool": "Tool",
|
||||
"mcpServers.logs.filter.allTools": "All tools",
|
||||
"mcpServers.logs.filter.person": "Person",
|
||||
"mcpServers.logs.filter.allPeople": "All people",
|
||||
"mcpServers.logs.filter.status": "Status",
|
||||
"mcpServers.logs.filter.anyStatus": "Any status",
|
||||
"mcpServers.logs.filter.dateRange": "Started",
|
||||
"mcpServers.logs.filter.startDate": "Earliest start",
|
||||
"mcpServers.logs.filter.endDate": "Latest start",
|
||||
"mcpServers.logs.filter.to": "to",
|
||||
"mcpServers.logs.filter.reset": "Reset filters",
|
||||
"mcpServers.logs.sort.label": "Sort tool calls",
|
||||
"mcpServers.logs.sort.newest": "Newest first",
|
||||
"mcpServers.logs.sort.oldest": "Oldest first",
|
||||
"mcpServers.logs.sort.longest": "Longest run time",
|
||||
"mcpServers.logs.sort.shortest": "Shortest run time",
|
||||
"mcpServers.logs.sort.toolAsc": "Tool (A to Z)",
|
||||
"mcpServers.logs.sort.toolDesc": "Tool (Z to A)",
|
||||
"mcpServers.logs.sort.statusAsc": "Status (errors first)",
|
||||
"mcpServers.logs.sort.statusDesc": "Status (succeeded first)",
|
||||
"mcp.workflowNotEligable.description": "Only published workflows with one of the following trigger nodes can be accessible via MCP: {triggers}",
|
||||
"mcp.instanceLevelAccessDisabled.description": "Instance-level MCP access is disabled. Enable it to allow workflow-level access.",
|
||||
"mcp.workflowDeactivated.title": "MCP access disabled",
|
||||
|
||||
@@ -6,8 +6,8 @@ and the [root AGENTS.md](../../../../../AGENTS.md) for repo-wide conventions.
|
||||
|
||||
## What the module owns
|
||||
|
||||
- The four tables: `mcp_server`, `mcp_server_tool`, `mcp_server_connection`, and `mcp_server_block`.
|
||||
- The REST routes for builders, overview listing, share pages, connections, and blocks.
|
||||
- The five tables: `mcp_server`, `mcp_server_tool`, `mcp_server_tool_call`, `mcp_server_connection`, and `mcp_server_block`.
|
||||
- The REST routes for builders, overview listing, share pages, connections, blocks, and tool call logs.
|
||||
- The stateless MCP runtime endpoint (`/mcp-servers/:slug`) and its per-server concurrency cap.
|
||||
- The OAuth protected resource resolver for AI client sign-in (`McpServerProtectedResource`).
|
||||
|
||||
@@ -91,7 +91,8 @@ This package exposes three entrypoints in `package.json`:
|
||||
| `createMcpServerTool`, `findMcpServerTools` | Create and read tool rows | `packages/cli/test/integration/mcp-servers/` |
|
||||
| `createMcpServerConnection`, `findMcpServerConnection`, `findMcpServerConnections`, `updateMcpServerConnectionLastUsedAt` | Create, read, and update connection rows | `packages/cli/test/integration/mcp-servers/` |
|
||||
| `createMcpServerBlock`, `findMcpServerBlocks` | Create and read block rows | `packages/cli/test/integration/mcp-servers/` |
|
||||
| `clearMcpServerTables` | Delete all rows from the four module tables between test cases | `packages/cli/test/integration/mcp-servers/` |
|
||||
| `createMcpServerToolCall`, `findMcpServerToolCalls` | Create and read tool call log rows | `packages/cli/test/integration/mcp-servers/` |
|
||||
| `clearMcpServerTables` | Delete all rows from the five module tables between test cases | `packages/cli/test/integration/mcp-servers/` |
|
||||
|
||||
Do not add symbols to `src/index.ts` or `src/testing/index.ts` unless a package outside this
|
||||
module imports them.
|
||||
|
||||
+25
-1
@@ -1,10 +1,12 @@
|
||||
import { ControllerRegistryMetadata } from '@n8n/decorators';
|
||||
import { Container } from '@n8n/di';
|
||||
|
||||
import { McpServerAccessController } from '../controllers/mcp-server-access.controller';
|
||||
import { McpServerRuntimeController } from '../controllers/mcp-server-runtime.controller';
|
||||
import { McpServerToolCallsController } from '../controllers/mcp-server-tool-calls.controller';
|
||||
import { McpServerToolsController } from '../controllers/mcp-server-tools.controller';
|
||||
import { McpServersListController } from '../controllers/mcp-servers-list.controller';
|
||||
import { McpServersController } from '../controllers/mcp-servers.controller';
|
||||
import { McpServerRuntimeController } from '../controllers/mcp-server-runtime.controller';
|
||||
|
||||
function routesOf(controller: object) {
|
||||
const metadata = Container.get(ControllerRegistryMetadata).getControllerMetadata(
|
||||
@@ -54,6 +56,28 @@ describe('McpServersListController route access scopes', () => {
|
||||
);
|
||||
});
|
||||
|
||||
describe('McpServerToolCallsController route access scopes', () => {
|
||||
it.each(routesOf(McpServerToolCallsController))(
|
||||
'$handlerName is gated by project-scoped mcpServer:read',
|
||||
({ route }) => {
|
||||
expect(route.skipAuth).toBeFalsy();
|
||||
expect(route.accessScope).toEqual({ scope: 'mcpServer:read', globalOnly: false });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('McpServerAccessController route access scopes', () => {
|
||||
it.each(routesOf(McpServerAccessController))(
|
||||
'$handlerName is gated by a project-scoped mcpServer:* check',
|
||||
({ route }) => {
|
||||
expect(route.skipAuth).toBeFalsy();
|
||||
expect(route.accessScope).toBeDefined();
|
||||
expect(route.accessScope?.globalOnly).toBe(false);
|
||||
expect(route.accessScope?.scope.startsWith('mcpServer:')).toBe(true);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('McpServerRuntimeController routes', () => {
|
||||
// The token check runs in the handler, so the routes skip the session and get an IP limit.
|
||||
it.each(routesOf(McpServerRuntimeController))(
|
||||
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
import { ListMcpServerToolCallsDto } from '@n8n/api-types';
|
||||
import { Person, ServiceAccount, type UserRepository } from '@n8n/db';
|
||||
import { mock } from 'vitest-mock-extended';
|
||||
|
||||
import type { McpServerToolCall } from '../database/entities/mcp-server-tool-call.entity';
|
||||
import type { McpServerTool } from '../database/entities/mcp-server-tool.entity';
|
||||
import type { McpServer } from '../database/entities/mcp-server.entity';
|
||||
import type { McpServerConnectionRepository } from '../database/repositories/mcp-server-connection.repository';
|
||||
import type { McpServerToolCallRepository } from '../database/repositories/mcp-server-tool-call.repository';
|
||||
import type { McpServerToolRepository } from '../database/repositories/mcp-server-tool.repository';
|
||||
import type { McpServerRepository } from '../database/repositories/mcp-server.repository';
|
||||
import { McpServerNotFoundError } from '../errors/mcp-server-not-found.error';
|
||||
import { McpServerToolCallsService } from '../services/mcp-server-tool-calls.service';
|
||||
|
||||
const PROJECT_ID = 'project-1';
|
||||
const SERVER_ID = '0190a8d6-4a2e-7000-8000-000000000001';
|
||||
const USER_MAYA = '0190a8d6-4a2e-7000-8000-0000000000a1';
|
||||
const USER_TOM = '0190a8d6-4a2e-7000-8000-0000000000a2';
|
||||
const USER_BOT = '0190a8d6-4a2e-7000-8000-0000000000a3';
|
||||
|
||||
function person(id: string, firstName: string, lastName: string, email: string): Person {
|
||||
return Object.assign(new Person(), { id, firstName, lastName, email });
|
||||
}
|
||||
|
||||
function makeCall(overrides: Partial<McpServerToolCall> = {}): McpServerToolCall {
|
||||
return Object.assign(
|
||||
{
|
||||
id: 1,
|
||||
serverId: SERVER_ID,
|
||||
toolId: '0190a8d6-4a2e-7000-8000-0000000000b1',
|
||||
toolName: 'get_pipeline',
|
||||
toolKind: 'workflow',
|
||||
targetId: 'wf-1',
|
||||
userId: USER_MAYA,
|
||||
oauthClientId: 'claude-code',
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 240,
|
||||
executionId: 'exec-42',
|
||||
errorMessage: null,
|
||||
startedAt: new Date('2026-11-24T10:00:00.000Z'),
|
||||
},
|
||||
overrides,
|
||||
) as McpServerToolCall;
|
||||
}
|
||||
|
||||
describe('McpServerToolCallsService', () => {
|
||||
const servers = mock<McpServerRepository>();
|
||||
const tools = mock<McpServerToolRepository>();
|
||||
const toolCalls = mock<McpServerToolCallRepository>();
|
||||
const connections = mock<McpServerConnectionRepository>();
|
||||
const users = mock<UserRepository>();
|
||||
const service = new McpServerToolCallsService(servers, tools, toolCalls, connections, users);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
servers.findInProject.mockResolvedValue({ id: SERVER_ID, projectId: PROJECT_ID } as McpServer);
|
||||
tools.listByServer.mockResolvedValue([
|
||||
{ toolName: 'create_deal' } as McpServerTool,
|
||||
{ toolName: 'get_pipeline' } as McpServerTool,
|
||||
]);
|
||||
toolCalls.listFilterOptions.mockResolvedValue({
|
||||
toolNames: ['get_pipeline', 'removed_tool'],
|
||||
userIds: [USER_TOM, USER_MAYA],
|
||||
});
|
||||
connections.listUserIdsByServer.mockResolvedValue([]);
|
||||
users.findManyByIds.mockResolvedValue([
|
||||
person(USER_MAYA, 'Maya', 'Fischer', 'maya@acme.com'),
|
||||
person(USER_TOM, 'Tom', 'Becker', 'tom@acme.com'),
|
||||
Object.assign(new ServiceAccount(), { id: USER_BOT }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('throws McpServerNotFoundError when serverId is not a UUID or does not belong to the project', async () => {
|
||||
await expect(
|
||||
service.list(PROJECT_ID, 'not-a-uuid', ListMcpServerToolCallsDto.parse({})),
|
||||
).rejects.toThrow(McpServerNotFoundError);
|
||||
expect(servers.findInProject).not.toHaveBeenCalled();
|
||||
|
||||
servers.findInProject.mockResolvedValueOnce(null);
|
||||
await expect(
|
||||
service.list(PROJECT_ID, SERVER_ID, ListMcpServerToolCallsDto.parse({})),
|
||||
).rejects.toThrow(McpServerNotFoundError);
|
||||
});
|
||||
|
||||
it('returns tool calls with resolved callers, sorted filter options, and null caller for deleted users', async () => {
|
||||
toolCalls.listByServer.mockResolvedValue({
|
||||
items: [
|
||||
makeCall({ id: 2, userId: USER_MAYA, status: 'success', executionId: 'exec-42' }),
|
||||
makeCall({
|
||||
id: 1,
|
||||
userId: null,
|
||||
toolId: null,
|
||||
toolName: 'removed_tool',
|
||||
status: 'error',
|
||||
executionId: null,
|
||||
errorMessage: 'The workflow of this tool no longer exists.',
|
||||
}),
|
||||
],
|
||||
total: 2,
|
||||
});
|
||||
|
||||
const result = await service.list(
|
||||
PROJECT_ID,
|
||||
SERVER_ID,
|
||||
ListMcpServerToolCallsDto.parse({
|
||||
status: 'error',
|
||||
startedAfter: '2026-11-24T00:00:00.000Z',
|
||||
sortBy: 'durationMs',
|
||||
sortDirection: 'asc',
|
||||
limit: 10,
|
||||
offset: 5,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(toolCalls.listByServer).toHaveBeenCalledWith(SERVER_ID, {
|
||||
toolName: undefined,
|
||||
userId: undefined,
|
||||
status: 'error',
|
||||
startedAfter: new Date('2026-11-24T00:00:00.000Z'),
|
||||
startedBefore: undefined,
|
||||
sortBy: 'durationMs',
|
||||
sortDirection: 'asc',
|
||||
limit: 10,
|
||||
offset: 5,
|
||||
});
|
||||
|
||||
expect(result.total).toBe(2);
|
||||
expect(result.items).toEqual([
|
||||
{
|
||||
id: 2,
|
||||
toolId: '0190a8d6-4a2e-7000-8000-0000000000b1',
|
||||
toolName: 'get_pipeline',
|
||||
toolKind: 'workflow',
|
||||
targetId: 'wf-1',
|
||||
caller: {
|
||||
userId: USER_MAYA,
|
||||
firstName: 'Maya',
|
||||
lastName: 'Fischer',
|
||||
email: 'maya@acme.com',
|
||||
},
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 240,
|
||||
executionId: 'exec-42',
|
||||
errorMessage: null,
|
||||
startedAt: '2026-11-24T10:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
toolId: null,
|
||||
toolName: 'removed_tool',
|
||||
toolKind: 'workflow',
|
||||
targetId: 'wf-1',
|
||||
caller: null,
|
||||
clientName: 'Claude Code',
|
||||
status: 'error',
|
||||
durationMs: 240,
|
||||
executionId: null,
|
||||
errorMessage: 'The workflow of this tool no longer exists.',
|
||||
startedAt: '2026-11-24T10:00:00.000Z',
|
||||
},
|
||||
]);
|
||||
|
||||
// Merges current server tools and logged tools alphabetically, and sorts callers by name.
|
||||
expect(result.filters).toEqual({
|
||||
tools: ['create_deal', 'get_pipeline', 'removed_tool'],
|
||||
callers: [
|
||||
{ userId: USER_MAYA, firstName: 'Maya', lastName: 'Fischer', email: 'maya@acme.com' },
|
||||
{ userId: USER_TOM, firstName: 'Tom', lastName: 'Becker', email: 'tom@acme.com' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('offers a person who connected but has no call in the recent window as a caller', async () => {
|
||||
toolCalls.listByServer.mockResolvedValue({ items: [], total: 0 });
|
||||
toolCalls.listFilterOptions.mockResolvedValue({ toolNames: [], userIds: [USER_MAYA] });
|
||||
connections.listUserIdsByServer.mockResolvedValue([USER_TOM]);
|
||||
|
||||
const result = await service.list(PROJECT_ID, SERVER_ID, ListMcpServerToolCallsDto.parse({}));
|
||||
|
||||
expect(connections.listUserIdsByServer).toHaveBeenCalledWith(SERVER_ID);
|
||||
expect(result.filters.callers.map((caller) => caller.userId)).toEqual([USER_MAYA, USER_TOM]);
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,7 @@ vi.mock('../controllers/mcp-servers.controller', () => ({}));
|
||||
vi.mock('../controllers/mcp-server-tools.controller', () => ({}));
|
||||
vi.mock('../controllers/mcp-server-runtime.controller', () => ({}));
|
||||
vi.mock('../controllers/mcp-server-access.controller', () => ({}));
|
||||
vi.mock('../controllers/mcp-server-tool-calls.controller', () => ({}));
|
||||
|
||||
describe('McpServersModule', () => {
|
||||
it('registers the module entrypoint', () => {
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import { ListMcpServerToolCallsDto, MCP_SERVER_ACTION_SCOPES } from '@n8n/api-types';
|
||||
import type { AuthenticatedRequest } from '@n8n/db';
|
||||
import { Get, ProjectScope, Query, RestController } from '@n8n/decorators';
|
||||
|
||||
import { CustomMcpServersFlagGate } from '../services/custom-mcp-servers-flag-gate';
|
||||
import { McpServerToolCallsService } from '../services/mcp-server-tool-calls.service';
|
||||
|
||||
type ServerRequest = AuthenticatedRequest<{ projectId: string; serverId: string }>;
|
||||
|
||||
/** Tool call log of a custom MCP server. */
|
||||
@RestController('/projects/:projectId/mcp-servers/:serverId')
|
||||
export class McpServerToolCallsController {
|
||||
constructor(
|
||||
private readonly flagGate: CustomMcpServersFlagGate,
|
||||
private readonly toolCalls: McpServerToolCallsService,
|
||||
) {}
|
||||
|
||||
@Get('/tool-calls')
|
||||
@ProjectScope(MCP_SERVER_ACTION_SCOPES.listToolCalls)
|
||||
async list(req: ServerRequest, _res: unknown, @Query dto: ListMcpServerToolCallsDto) {
|
||||
await this.flagGate.assertEnabled();
|
||||
return await this.toolCalls.list(req.params.projectId, req.params.serverId, dto);
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
import type { McpServerToolCallStatus, McpServerToolKind } from '@n8n/api-types';
|
||||
import { DateTimeColumn, dbNowLiteral, dbType } from '@n8n/db';
|
||||
import { BaseEntity, Column, Entity, Index, PrimaryGeneratedColumn } from '@n8n/typeorm';
|
||||
|
||||
// The migration has the same default. Without it on the entity, TypeORM inserts NULL on SQLite.
|
||||
const DB_NOW = dbNowLiteral(dbType === 'postgresdb');
|
||||
|
||||
/** One tool call made by an AI client through a custom MCP server. */
|
||||
@Entity({ name: 'mcp_server_tool_call' })
|
||||
@Index(['serverId', 'startedAt', 'id'])
|
||||
@Index(['startedAt'])
|
||||
@Index(['serverId', 'durationMs', 'id'])
|
||||
@Index(['serverId', 'toolName', 'id'])
|
||||
@Index(['serverId', 'status', 'id'])
|
||||
export class McpServerToolCall extends BaseEntity {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column({ type: 'uuid' })
|
||||
serverId: string;
|
||||
|
||||
@Index()
|
||||
@Column({ type: 'uuid', nullable: true })
|
||||
toolId: string | null;
|
||||
|
||||
@Column({ type: 'varchar', length: 64 })
|
||||
toolName: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 16 })
|
||||
toolKind: McpServerToolKind;
|
||||
|
||||
@Column({ type: 'varchar', length: 36, nullable: true })
|
||||
targetId: string | null;
|
||||
|
||||
@Index()
|
||||
@Column({ type: 'uuid', nullable: true })
|
||||
userId: string | null;
|
||||
|
||||
@Index()
|
||||
@Column({ type: 'varchar', nullable: true })
|
||||
oauthClientId: string | null;
|
||||
|
||||
@Column({ type: 'varchar', length: 255 })
|
||||
clientName: string;
|
||||
|
||||
@Column({ type: 'varchar', length: 16 })
|
||||
status: McpServerToolCallStatus;
|
||||
|
||||
@Column({ type: 'int' })
|
||||
durationMs: number;
|
||||
|
||||
@Column({ type: 'varchar', length: 36, nullable: true })
|
||||
executionId: string | null;
|
||||
|
||||
@Column({ type: 'text', nullable: true })
|
||||
errorMessage: string | null;
|
||||
|
||||
@DateTimeColumn({ precision: 3, default: () => DB_NOW })
|
||||
startedAt: Date;
|
||||
}
|
||||
+11
@@ -108,6 +108,17 @@ export class McpServerConnectionRepository {
|
||||
});
|
||||
}
|
||||
|
||||
/** The IDs of the people who connected to the server, each one time. */
|
||||
async listUserIdsByServer(serverId: string, ctx: OperationContext = {}): Promise<string[]> {
|
||||
const rows = await this.table
|
||||
.managerFor(ctx)
|
||||
.createQueryBuilder(McpServerConnection, 'connection')
|
||||
.select('DISTINCT connection.userId', 'userId')
|
||||
.where('connection.serverId = :serverId', { serverId })
|
||||
.getRawMany<{ userId: string }>();
|
||||
return rows.map((row) => row.userId);
|
||||
}
|
||||
|
||||
/** The number of people with at least one active (not blocked) client, for each server. */
|
||||
async countActiveByServers(
|
||||
serverIds: string[],
|
||||
|
||||
+319
@@ -0,0 +1,319 @@
|
||||
import {
|
||||
MCP_SERVER_TOOL_CALLS_MAX_ROWS,
|
||||
type McpServerToolCallSortBy,
|
||||
type McpServerToolCallSortDirection,
|
||||
type McpServerToolCallStatus,
|
||||
} from '@n8n/api-types';
|
||||
import {
|
||||
BaseRepository,
|
||||
isForeignKeyConstraintError,
|
||||
TransactionRunner,
|
||||
User,
|
||||
type OperationContext,
|
||||
} from '@n8n/db';
|
||||
import { Service } from '@n8n/di';
|
||||
import { DataSource, type SelectQueryBuilder } from '@n8n/typeorm';
|
||||
|
||||
import { McpServerToolCall } from '../entities/mcp-server-tool-call.entity';
|
||||
import { McpServerTool } from '../entities/mcp-server-tool.entity';
|
||||
|
||||
class McpServerToolCallTable extends BaseRepository<McpServerToolCall> {
|
||||
constructor(dataSource: DataSource, transactionRunner: TransactionRunner) {
|
||||
super(McpServerToolCall, dataSource.manager, transactionRunner);
|
||||
}
|
||||
}
|
||||
|
||||
export type NewMcpServerToolCall = Pick<
|
||||
McpServerToolCall,
|
||||
| 'serverId'
|
||||
| 'toolId'
|
||||
| 'toolName'
|
||||
| 'toolKind'
|
||||
| 'targetId'
|
||||
| 'userId'
|
||||
| 'oauthClientId'
|
||||
| 'clientName'
|
||||
| 'status'
|
||||
| 'durationMs'
|
||||
| 'executionId'
|
||||
| 'errorMessage'
|
||||
| 'startedAt'
|
||||
>;
|
||||
|
||||
export type McpServerToolCallFixtureRow = Pick<
|
||||
McpServerToolCall,
|
||||
'serverId' | 'toolName' | 'clientName' | 'status' | 'durationMs'
|
||||
> &
|
||||
Partial<
|
||||
Pick<
|
||||
McpServerToolCall,
|
||||
| 'toolId'
|
||||
| 'toolKind'
|
||||
| 'targetId'
|
||||
| 'userId'
|
||||
| 'oauthClientId'
|
||||
| 'executionId'
|
||||
| 'errorMessage'
|
||||
| 'startedAt'
|
||||
>
|
||||
>;
|
||||
|
||||
export interface McpServerToolCallQuery {
|
||||
toolName?: string;
|
||||
userId?: string;
|
||||
status?: McpServerToolCallStatus;
|
||||
startedAfter?: Date;
|
||||
startedBefore?: Date;
|
||||
sortBy: McpServerToolCallSortBy;
|
||||
sortDirection: McpServerToolCallSortDirection;
|
||||
limit: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export interface McpServerToolCallFilterOptions {
|
||||
toolNames: string[];
|
||||
userIds: string[];
|
||||
}
|
||||
|
||||
/** Status order for the sort: errors, then unfinished runs, then successes. */
|
||||
const STATUS_ORDER: McpServerToolCallStatus[] = ['error', 'unfinished', 'success'];
|
||||
|
||||
type TableManager = ReturnType<McpServerToolCallTable['managerFor']>;
|
||||
|
||||
const SORT_COLUMNS: Record<Exclude<McpServerToolCallSortBy, 'status'>, string> = {
|
||||
startedAt: 'call.startedAt',
|
||||
durationMs: 'call.durationMs',
|
||||
toolName: 'call.toolName',
|
||||
};
|
||||
|
||||
/** Max recent calls inspected when deriving filter options so cost stays bounded as history grows. */
|
||||
const FILTER_OPTIONS_WINDOW = 1000;
|
||||
|
||||
@Service()
|
||||
export class McpServerToolCallRepository {
|
||||
private readonly table: McpServerToolCallTable;
|
||||
|
||||
constructor(dataSource: DataSource, transactionRunner: TransactionRunner) {
|
||||
this.table = new McpServerToolCallTable(dataSource, transactionRunner);
|
||||
}
|
||||
|
||||
async insert(row: NewMcpServerToolCall, ctx: OperationContext = {}): Promise<void> {
|
||||
const manager = this.table.managerFor(ctx);
|
||||
try {
|
||||
await manager.insert(McpServerToolCall, row);
|
||||
} catch (error) {
|
||||
if (
|
||||
ctx.trx ||
|
||||
!isForeignKeyConstraintError(error) ||
|
||||
(row.toolId === null && row.userId === null && row.oauthClientId === null)
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
// A tool, user, or OAuth client can be deleted while a call is in flight; keep the log row
|
||||
// while preserving every foreign-key reference that still exists.
|
||||
const [toolExists, userExists] = await Promise.all([
|
||||
row.toolId !== null ? manager.existsBy(McpServerTool, { id: row.toolId }) : true,
|
||||
row.userId !== null ? manager.existsBy(User, { id: row.userId }) : true,
|
||||
]);
|
||||
const next: NewMcpServerToolCall = {
|
||||
...row,
|
||||
toolId: toolExists ? row.toolId : null,
|
||||
userId: userExists ? row.userId : null,
|
||||
};
|
||||
if (next.toolId !== row.toolId || next.userId !== row.userId) {
|
||||
try {
|
||||
await manager.insert(McpServerToolCall, next);
|
||||
return;
|
||||
} catch (retryError) {
|
||||
if (!isForeignKeyConstraintError(retryError) || next.oauthClientId === null) {
|
||||
throw retryError;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (next.oauthClientId === null) {
|
||||
throw error;
|
||||
}
|
||||
await manager.insert(McpServerToolCall, {
|
||||
...next,
|
||||
oauthClientId: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One page of the server's calls, and the number of matching calls. The count stops at
|
||||
* `MCP_SERVER_TOOL_CALLS_MAX_ROWS`, so a long history does not make each page load slow.
|
||||
*/
|
||||
async listByServer(
|
||||
serverId: string,
|
||||
query: McpServerToolCallQuery,
|
||||
ctx: OperationContext = {},
|
||||
): Promise<{ items: McpServerToolCall[]; total: number }> {
|
||||
const manager = this.table.managerFor(ctx);
|
||||
const direction = query.sortDirection === 'asc' ? 'ASC' : 'DESC';
|
||||
// A page stops at the same cap as the count, so paging never goes past `total`.
|
||||
const pageSize = Math.min(query.limit, MCP_SERVER_TOOL_CALLS_MAX_ROWS - query.offset);
|
||||
let items: McpServerToolCall[] = [];
|
||||
if (pageSize > 0) {
|
||||
items =
|
||||
query.sortBy === 'status'
|
||||
? await this.pageByStatus(manager, serverId, query, direction, pageSize)
|
||||
: await this.whereMatches(
|
||||
manager.createQueryBuilder(McpServerToolCall, 'call'),
|
||||
serverId,
|
||||
query,
|
||||
)
|
||||
.orderBy(SORT_COLUMNS[query.sortBy], direction)
|
||||
.addOrderBy('call.id', direction)
|
||||
.offset(query.offset)
|
||||
.limit(pageSize)
|
||||
.getMany();
|
||||
}
|
||||
|
||||
return { items, total: await this.cappedCount(manager, serverId, query) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The status order is not alphabetical. Each status group is read in turn through the
|
||||
* `(serverId, status, id)` index, so a page never sorts every row of the server.
|
||||
*/
|
||||
private async pageByStatus(
|
||||
manager: TableManager,
|
||||
serverId: string,
|
||||
query: McpServerToolCallQuery,
|
||||
direction: 'ASC' | 'DESC',
|
||||
pageSize: number,
|
||||
): Promise<McpServerToolCall[]> {
|
||||
const order = direction === 'ASC' ? STATUS_ORDER : [...STATUS_ORDER].reverse();
|
||||
const statuses = query.status ? order.filter((status) => status === query.status) : order;
|
||||
const items: McpServerToolCall[] = [];
|
||||
let skip = query.offset;
|
||||
for (const status of statuses) {
|
||||
const remaining = pageSize - items.length;
|
||||
if (remaining <= 0) break;
|
||||
const groupQuery = { ...query, status };
|
||||
const groupSize = await this.cappedCount(manager, serverId, groupQuery);
|
||||
if (skip >= groupSize) {
|
||||
skip -= groupSize;
|
||||
continue;
|
||||
}
|
||||
items.push(
|
||||
...(await this.whereMatches(
|
||||
manager.createQueryBuilder(McpServerToolCall, 'call'),
|
||||
serverId,
|
||||
groupQuery,
|
||||
)
|
||||
.orderBy('call.id', direction)
|
||||
.offset(skip)
|
||||
.limit(remaining)
|
||||
.getMany()),
|
||||
);
|
||||
skip = 0;
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** The number of matching calls, counted up to `MCP_SERVER_TOOL_CALLS_MAX_ROWS`. */
|
||||
private async cappedCount(
|
||||
manager: TableManager,
|
||||
serverId: string,
|
||||
query: McpServerToolCallQuery,
|
||||
): Promise<number> {
|
||||
const counted = await manager
|
||||
.createQueryBuilder()
|
||||
.select('COUNT(*)', 'count')
|
||||
.from(
|
||||
(sub) =>
|
||||
this.whereMatches(
|
||||
sub.select('call.id').from(McpServerToolCall, 'call'),
|
||||
serverId,
|
||||
query,
|
||||
).limit(MCP_SERVER_TOOL_CALLS_MAX_ROWS),
|
||||
'capped',
|
||||
)
|
||||
.getRawOne<{ count: number | string }>();
|
||||
return Number(counted?.count ?? 0);
|
||||
}
|
||||
|
||||
private whereMatches<T extends SelectQueryBuilder<McpServerToolCall>>(
|
||||
qb: T,
|
||||
serverId: string,
|
||||
query: McpServerToolCallQuery,
|
||||
): T {
|
||||
qb.where('call.serverId = :serverId', { serverId });
|
||||
if (query.toolName) {
|
||||
qb.andWhere('call.toolName = :toolName', { toolName: query.toolName });
|
||||
}
|
||||
if (query.userId) {
|
||||
qb.andWhere('call.userId = :userId', { userId: query.userId });
|
||||
}
|
||||
if (query.status) {
|
||||
qb.andWhere('call.status = :status', { status: query.status });
|
||||
}
|
||||
if (query.startedAfter) {
|
||||
qb.andWhere('call.startedAt >= :startedAfter', { startedAfter: query.startedAfter });
|
||||
}
|
||||
if (query.startedBefore) {
|
||||
qb.andWhere('call.startedAt <= :startedBefore', { startedBefore: query.startedBefore });
|
||||
}
|
||||
return qb;
|
||||
}
|
||||
|
||||
/** Distinct tool names and non-null caller user IDs from the server's most recent calls. */
|
||||
async listFilterOptions(
|
||||
serverId: string,
|
||||
ctx: OperationContext = {},
|
||||
): Promise<McpServerToolCallFilterOptions> {
|
||||
const rows = await this.table
|
||||
.managerFor(ctx)
|
||||
.createQueryBuilder(McpServerToolCall, 'call')
|
||||
.select('call.toolName', 'toolName')
|
||||
.addSelect('call.userId', 'userId')
|
||||
.where('call.serverId = :serverId', { serverId })
|
||||
.orderBy('call.startedAt', 'DESC')
|
||||
.addOrderBy('call.id', 'DESC')
|
||||
.limit(FILTER_OPTIONS_WINDOW)
|
||||
.getRawMany<{ toolName: string; userId: string | null }>();
|
||||
|
||||
const toolNames = new Set<string>();
|
||||
const userIds = new Set<string>();
|
||||
for (const row of rows) {
|
||||
toolNames.add(row.toolName);
|
||||
if (row.userId !== null) userIds.add(row.userId);
|
||||
}
|
||||
|
||||
return {
|
||||
toolNames: [...toolNames],
|
||||
userIds: [...userIds],
|
||||
};
|
||||
}
|
||||
|
||||
/** Inserts a tool call row with defaults for optional fields. For test fixtures. */
|
||||
async insertFixture(row: McpServerToolCallFixtureRow): Promise<McpServerToolCall> {
|
||||
const result = await this.table.manager.insert(McpServerToolCall, {
|
||||
toolId: null,
|
||||
toolKind: 'workflow',
|
||||
targetId: null,
|
||||
userId: null,
|
||||
oauthClientId: null,
|
||||
executionId: null,
|
||||
errorMessage: null,
|
||||
...row,
|
||||
});
|
||||
const id = Number(result.identifiers[0]?.id);
|
||||
return await this.table.manager.findOneByOrFail(McpServerToolCall, { id });
|
||||
}
|
||||
|
||||
/** Lists every tool call row of one server, or across all servers. For test fixtures. */
|
||||
async findAll(serverId?: string): Promise<McpServerToolCall[]> {
|
||||
return await this.table.manager.find(McpServerToolCall, {
|
||||
...(serverId ? { where: { serverId } } : {}),
|
||||
order: { startedAt: 'DESC', id: 'DESC' },
|
||||
});
|
||||
}
|
||||
|
||||
/** Deletes every tool call row. For test fixtures. */
|
||||
async deleteAll(): Promise<void> {
|
||||
await this.table.manager.delete(McpServerToolCall, {});
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ export class McpServersModule implements ModuleInterface {
|
||||
await import('./controllers/mcp-server-tools.controller.js');
|
||||
await import('./controllers/mcp-server-share.controller.js');
|
||||
await import('./controllers/mcp-server-access.controller.js');
|
||||
await import('./controllers/mcp-server-tool-calls.controller.js');
|
||||
await import('./controllers/mcp-server-runtime.controller.js');
|
||||
const { ProtectedResourceRegistry } = await import('@n8n/backend-services/auth');
|
||||
const { McpServerProtectedResource } = await import(
|
||||
@@ -45,10 +46,20 @@ export class McpServersModule implements ModuleInterface {
|
||||
'./database/entities/mcp-server-reserved-slug.entity.js'
|
||||
);
|
||||
const { McpServerTool } = await import('./database/entities/mcp-server-tool.entity.js');
|
||||
const { McpServerToolCall } = await import(
|
||||
'./database/entities/mcp-server-tool-call.entity.js'
|
||||
);
|
||||
const { McpServerConnection } = await import(
|
||||
'./database/entities/mcp-server-connection.entity.js'
|
||||
);
|
||||
const { McpServerBlock } = await import('./database/entities/mcp-server-block.entity.js');
|
||||
return [McpServer, McpServerReservedSlug, McpServerTool, McpServerConnection, McpServerBlock];
|
||||
return [
|
||||
McpServer,
|
||||
McpServerReservedSlug,
|
||||
McpServerTool,
|
||||
McpServerToolCall,
|
||||
McpServerConnection,
|
||||
McpServerBlock,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { McpServerToolCallStatus } from '@n8n/api-types';
|
||||
import { Logger } from '@n8n/backend-common';
|
||||
import { EventService } from '@n8n/backend-services';
|
||||
import { ensureError } from '@n8n/utils/errors/ensure-error';
|
||||
import { isRecord } from '@n8n/utils/is-record';
|
||||
import { lazyImport } from '@n8n/utils/lazy-import';
|
||||
import { Service } from '@n8n/di';
|
||||
@@ -14,6 +17,7 @@ import type { SecurityContext } from '@n8n/permissions';
|
||||
|
||||
import type { McpServerTool } from '../database/entities/mcp-server-tool.entity';
|
||||
import type { McpServer } from '../database/entities/mcp-server.entity';
|
||||
import { McpServerToolCallRepository } from '../database/repositories/mcp-server-tool-call.repository';
|
||||
import { McpServerToolRepository } from '../database/repositories/mcp-server-tool.repository';
|
||||
import { AgentToolPort, type AgentToolRefusal } from '../ports/agent-tool.port';
|
||||
import { NodeToolPort, type NodeToolRefusal } from '../ports/node-tool.port';
|
||||
@@ -59,6 +63,7 @@ export const SERVER_BUSY_MESSAGE = 'The server is busy. Try again in a moment.';
|
||||
const STOP_AND_ERROR_NODE_TYPE = 'n8n-nodes-base.stopAndError';
|
||||
const GENERIC_FAILURE_MESSAGE =
|
||||
'The workflow of this tool failed. A builder of the server can see the details in its executions.';
|
||||
const UNEXPECTED_FAILURE_MESSAGE = 'The tool call failed. Check the server logs for details.';
|
||||
|
||||
const REFUSAL_MESSAGES: Record<WorkflowToolRefusal, string> = {
|
||||
not_found: 'The workflow of this tool no longer exists. Ask a builder of the server to fix it.',
|
||||
@@ -117,9 +122,22 @@ const RUN_STATUS_MESSAGES = {
|
||||
unknown: 'The workflow run ended without a result.',
|
||||
} as const;
|
||||
|
||||
const CLIENT_NAME_MAX_LENGTH = 255;
|
||||
const ERROR_MESSAGE_MAX_LENGTH = 2000;
|
||||
const UNKNOWN_CLIENT_NAME = 'Unknown client';
|
||||
|
||||
export type McpServerCaller = { userId: string; clientId?: string };
|
||||
|
||||
type CallOutcome = { result: CallToolResult; status: 'success' | 'error' };
|
||||
type CallOutcome = {
|
||||
result: CallToolResult;
|
||||
status: McpServerToolCallStatus;
|
||||
executionId?: string;
|
||||
errorMessage?: string;
|
||||
};
|
||||
|
||||
function truncateCodePoints(value: string, maxLength: number): string {
|
||||
return Array.from(value).slice(0, maxLength).join('');
|
||||
}
|
||||
|
||||
function isJsonValue(value: unknown): value is JSONValue {
|
||||
if (value === null || ['string', 'number', 'boolean'].includes(typeof value)) return true;
|
||||
@@ -166,12 +184,14 @@ export class McpServerRuntimeService {
|
||||
private readonly resources: McpServerProtectedResource,
|
||||
private readonly admission: ResourceAdmission,
|
||||
private readonly tools: McpServerToolRepository,
|
||||
private readonly toolCalls: McpServerToolCallRepository,
|
||||
private readonly workflows: WorkflowToolPort,
|
||||
private readonly clients: OAuthClientNamePort,
|
||||
private readonly runCap: McpServerRunCap,
|
||||
private readonly events: EventService,
|
||||
private readonly agents: AgentToolPort,
|
||||
private readonly nodes: NodeToolPort,
|
||||
private readonly logger: Logger,
|
||||
) {}
|
||||
|
||||
/** Checks the token and the connect scope of the person, for this server only. */
|
||||
@@ -219,6 +239,7 @@ export class McpServerRuntimeService {
|
||||
mcp.setRequestHandler('tools/call', async (request) => {
|
||||
const tool = await this.tools.findByName(server.id, request.params.name);
|
||||
if (!tool) {
|
||||
// Protocol-level InvalidParams errors have no tool or toolKind; skip logging so arbitrary client names do not pollute the log or filter list.
|
||||
throw new ProtocolError(
|
||||
ProtocolErrorCode.InvalidParams,
|
||||
`Unknown tool: ${request.params.name}`,
|
||||
@@ -284,16 +305,37 @@ export class McpServerRuntimeService {
|
||||
request: CallToolRequest,
|
||||
caller: McpServerCaller,
|
||||
): Promise<CallOutcome | { invalidInput: string }> {
|
||||
const startedAt = Date.now();
|
||||
const startedAt = new Date();
|
||||
let outcome: CallOutcome | { invalidInput: string };
|
||||
try {
|
||||
outcome = await this.runTool(server, tool, request.params.arguments ?? {}, caller);
|
||||
} catch (error) {
|
||||
await this.trackCall(server, tool, caller, 'error', Date.now() - startedAt);
|
||||
await this.recordAndTrackCall(server, tool, caller, {
|
||||
status: 'error',
|
||||
startedAt,
|
||||
durationMs: Math.max(0, Date.now() - startedAt.getTime()),
|
||||
executionId: null,
|
||||
errorMessage: UNEXPECTED_FAILURE_MESSAGE,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
const status = 'invalidInput' in outcome ? 'error' : outcome.status;
|
||||
await this.trackCall(server, tool, caller, status, Date.now() - startedAt);
|
||||
const details =
|
||||
'invalidInput' in outcome
|
||||
? {
|
||||
status: 'error' as const,
|
||||
startedAt,
|
||||
durationMs: Math.max(0, Date.now() - startedAt.getTime()),
|
||||
executionId: null,
|
||||
errorMessage: outcome.invalidInput,
|
||||
}
|
||||
: {
|
||||
status: outcome.status,
|
||||
startedAt,
|
||||
durationMs: Math.max(0, Date.now() - startedAt.getTime()),
|
||||
executionId: outcome.executionId ?? null,
|
||||
errorMessage: outcome.errorMessage ?? null,
|
||||
};
|
||||
await this.recordAndTrackCall(server, tool, caller, details);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
@@ -305,7 +347,11 @@ export class McpServerRuntimeService {
|
||||
): Promise<CallOutcome | { invalidInput: string }> {
|
||||
if (tool.kind === 'node') return await this.runNodeTool(server, tool, input);
|
||||
if (!tool.targetId) {
|
||||
return { status: 'error', result: errorResult(REFUSAL_MESSAGES.not_found) };
|
||||
return {
|
||||
status: 'error',
|
||||
result: errorResult(REFUSAL_MESSAGES.not_found),
|
||||
errorMessage: REFUSAL_MESSAGES.not_found,
|
||||
};
|
||||
}
|
||||
switch (tool.kind) {
|
||||
case 'workflow':
|
||||
@@ -313,7 +359,11 @@ export class McpServerRuntimeService {
|
||||
case 'agent':
|
||||
return await this.runAgentTool(server, tool.targetId, input, caller);
|
||||
default:
|
||||
return { status: 'error', result: errorResult(REFUSAL_MESSAGES.not_found) };
|
||||
return {
|
||||
status: 'error',
|
||||
result: errorResult(REFUSAL_MESSAGES.not_found),
|
||||
errorMessage: REFUSAL_MESSAGES.not_found,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,7 +374,11 @@ export class McpServerRuntimeService {
|
||||
): Promise<CallOutcome | { invalidInput: string }> {
|
||||
const node = readNodeTool(tool.toolData);
|
||||
if (!node) {
|
||||
return { status: 'error', result: errorResult(NODE_REFUSAL_MESSAGES.node_unavailable) };
|
||||
return {
|
||||
status: 'error',
|
||||
result: errorResult(NODE_REFUSAL_MESSAGES.node_unavailable),
|
||||
errorMessage: NODE_REFUSAL_MESSAGES.node_unavailable,
|
||||
};
|
||||
}
|
||||
const run = await this.inRunSlot(
|
||||
server.id,
|
||||
@@ -333,11 +387,19 @@ export class McpServerRuntimeService {
|
||||
waitMs: RUN_WAIT_MS,
|
||||
}),
|
||||
);
|
||||
if (!run) return { status: 'error', result: errorResult(SERVER_BUSY_MESSAGE) };
|
||||
if (!run) {
|
||||
return {
|
||||
status: 'error',
|
||||
result: errorResult(SERVER_BUSY_MESSAGE),
|
||||
errorMessage: SERVER_BUSY_MESSAGE,
|
||||
};
|
||||
}
|
||||
|
||||
switch (run.status) {
|
||||
case 'refused':
|
||||
return { status: 'error', result: errorResult(NODE_REFUSAL_MESSAGES[run.reason]) };
|
||||
case 'refused': {
|
||||
const message = NODE_REFUSAL_MESSAGES[run.reason];
|
||||
return { status: 'error', result: errorResult(message), errorMessage: message };
|
||||
}
|
||||
case 'invalid_input':
|
||||
return { invalidInput: run.message };
|
||||
case 'success':
|
||||
@@ -346,9 +408,17 @@ export class McpServerRuntimeService {
|
||||
result: { content: [{ type: 'text', text: JSON.stringify(run.output) }] },
|
||||
};
|
||||
case 'error':
|
||||
return { status: 'error', result: errorResult(run.message) };
|
||||
return {
|
||||
status: 'error',
|
||||
result: errorResult(run.message),
|
||||
errorMessage: run.message,
|
||||
};
|
||||
case 'running':
|
||||
return { status: 'error', result: errorResult(NODE_RUNNING_MESSAGE) };
|
||||
return {
|
||||
status: 'unfinished',
|
||||
result: errorResult(NODE_RUNNING_MESSAGE),
|
||||
errorMessage: NODE_RUNNING_MESSAGE,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -376,11 +446,19 @@ export class McpServerRuntimeService {
|
||||
{ waitMs: RUN_WAIT_MS, maxRunMs: AGENT_MAX_RUN_MS },
|
||||
),
|
||||
);
|
||||
if (!run) return { status: 'error', result: errorResult(SERVER_BUSY_MESSAGE) };
|
||||
if (!run) {
|
||||
return {
|
||||
status: 'error',
|
||||
result: errorResult(SERVER_BUSY_MESSAGE),
|
||||
errorMessage: SERVER_BUSY_MESSAGE,
|
||||
};
|
||||
}
|
||||
|
||||
switch (run.status) {
|
||||
case 'refused':
|
||||
return { status: 'error', result: errorResult(AGENT_REFUSAL_MESSAGES[run.reason]) };
|
||||
case 'refused': {
|
||||
const message = AGENT_REFUSAL_MESSAGES[run.reason];
|
||||
return { status: 'error', result: errorResult(message), errorMessage: message };
|
||||
}
|
||||
case 'success': {
|
||||
const answer = {
|
||||
response: run.text,
|
||||
@@ -393,10 +471,14 @@ export class McpServerRuntimeService {
|
||||
result: { content: [{ type: 'text', text: JSON.stringify(answer) }] },
|
||||
};
|
||||
}
|
||||
case 'error':
|
||||
return { status: 'error', result: errorResult(run.message ?? AGENT_FAILURE_MESSAGE) };
|
||||
case 'running':
|
||||
return { status: 'error', result: errorResult(agentRunningMessage(run.sessionId)) };
|
||||
case 'error': {
|
||||
const message = run.message ?? AGENT_FAILURE_MESSAGE;
|
||||
return { status: 'error', result: errorResult(message), errorMessage: message };
|
||||
}
|
||||
case 'running': {
|
||||
const message = agentRunningMessage(run.sessionId);
|
||||
return { status: 'unfinished', result: errorResult(message), errorMessage: message };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,7 +490,11 @@ export class McpServerRuntimeService {
|
||||
): Promise<CallOutcome | { invalidInput: string }> {
|
||||
const prepared = await this.prepareInputs(server, tool, workflowId, input);
|
||||
if (!prepared.ok) {
|
||||
return { status: 'error', result: errorResult(prepared.error) };
|
||||
return {
|
||||
status: 'error',
|
||||
result: errorResult(prepared.error),
|
||||
errorMessage: prepared.error,
|
||||
};
|
||||
}
|
||||
|
||||
const run = await this.inRunSlot(
|
||||
@@ -418,32 +504,56 @@ export class McpServerRuntimeService {
|
||||
waitMs: RUN_WAIT_MS,
|
||||
}),
|
||||
);
|
||||
if (!run) return { status: 'error', result: errorResult(SERVER_BUSY_MESSAGE) };
|
||||
if (!run) {
|
||||
return {
|
||||
status: 'error',
|
||||
result: errorResult(SERVER_BUSY_MESSAGE),
|
||||
errorMessage: SERVER_BUSY_MESSAGE,
|
||||
};
|
||||
}
|
||||
|
||||
switch (run.status) {
|
||||
case 'refused':
|
||||
return { status: 'error', result: errorResult(REFUSAL_MESSAGES[run.reason]) };
|
||||
case 'refused': {
|
||||
const message = REFUSAL_MESSAGES[run.reason];
|
||||
return { status: 'error', result: errorResult(message), errorMessage: message };
|
||||
}
|
||||
case 'invalid_input':
|
||||
return { invalidInput: run.message };
|
||||
case 'busy':
|
||||
return { status: 'error', result: errorResult(SERVER_BUSY_MESSAGE) };
|
||||
return {
|
||||
status: 'error',
|
||||
result: errorResult(SERVER_BUSY_MESSAGE),
|
||||
errorMessage: SERVER_BUSY_MESSAGE,
|
||||
};
|
||||
case 'success':
|
||||
return {
|
||||
status: 'success',
|
||||
executionId: run.executionId,
|
||||
result: { content: [{ type: 'text', text: JSON.stringify(run.output) }] },
|
||||
};
|
||||
case 'error':
|
||||
case 'error': {
|
||||
// Other error texts can name hosts and tables of a private workflow.
|
||||
const message =
|
||||
run.error.nodeType === STOP_AND_ERROR_NODE_TYPE
|
||||
? run.error.message
|
||||
: GENERIC_FAILURE_MESSAGE;
|
||||
return {
|
||||
status: 'error',
|
||||
result: errorResult(
|
||||
run.error.nodeType === STOP_AND_ERROR_NODE_TYPE
|
||||
? run.error.message
|
||||
: GENERIC_FAILURE_MESSAGE,
|
||||
),
|
||||
executionId: run.executionId,
|
||||
errorMessage: message,
|
||||
result: errorResult(message),
|
||||
};
|
||||
default:
|
||||
return { status: 'error', result: errorResult(RUN_STATUS_MESSAGES[run.status]) };
|
||||
}
|
||||
default: {
|
||||
const message = RUN_STATUS_MESSAGES[run.status];
|
||||
return {
|
||||
// A running or waiting execution can still succeed: "View execution" shows the end.
|
||||
status: run.status === 'running' || run.status === 'waiting' ? 'unfinished' : 'error',
|
||||
executionId: run.executionId,
|
||||
errorMessage: message,
|
||||
result: errorResult(message),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -495,24 +605,56 @@ export class McpServerRuntimeService {
|
||||
return { ok: true, input: applyFixedInputs(input, settings, declaredNames) };
|
||||
}
|
||||
|
||||
private async trackCall(
|
||||
private async recordAndTrackCall(
|
||||
server: McpServer,
|
||||
tool: McpServerTool,
|
||||
caller: McpServerCaller,
|
||||
status: 'success' | 'error',
|
||||
durationMs: number,
|
||||
details: {
|
||||
status: McpServerToolCallStatus;
|
||||
startedAt: Date;
|
||||
durationMs: number;
|
||||
executionId: string | null;
|
||||
errorMessage: string | null;
|
||||
},
|
||||
): Promise<void> {
|
||||
// The client name only labels the event. A failed lookup must not fail the call.
|
||||
const clientName = caller.clientId
|
||||
// The client name only labels the log and event. A failed lookup must not fail the call.
|
||||
const registered = caller.clientId
|
||||
? await this.clients.getName(caller.clientId).catch(() => undefined)
|
||||
: undefined;
|
||||
|
||||
// Recording the log entry only informs builders. A failed write must not fail the tool call.
|
||||
try {
|
||||
await this.toolCalls.insert({
|
||||
serverId: server.id,
|
||||
toolId: tool.id,
|
||||
toolName: tool.toolName,
|
||||
toolKind: tool.kind,
|
||||
targetId: tool.targetId,
|
||||
userId: caller.userId,
|
||||
oauthClientId: caller.clientId ?? null,
|
||||
clientName: truncateCodePoints(registered || UNKNOWN_CLIENT_NAME, CLIENT_NAME_MAX_LENGTH),
|
||||
status: details.status,
|
||||
durationMs: details.durationMs,
|
||||
executionId: details.executionId,
|
||||
errorMessage: details.errorMessage
|
||||
? truncateCodePoints(details.errorMessage, ERROR_MESSAGE_MAX_LENGTH)
|
||||
: null,
|
||||
startedAt: details.startedAt,
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.warn('Could not record a custom MCP server tool call', {
|
||||
error: ensureError(error).message,
|
||||
});
|
||||
}
|
||||
|
||||
this.events.emit('mcp-server-tool-called', {
|
||||
serverId: server.id,
|
||||
userId: caller.userId,
|
||||
clientName: clientName ?? 'unknown',
|
||||
clientName: registered ?? 'unknown',
|
||||
toolKind: tool.kind,
|
||||
status,
|
||||
durationMs,
|
||||
// The event keeps two values: a call that returned without a result did not succeed.
|
||||
status: details.status === 'success' ? 'success' : 'error',
|
||||
durationMs: details.durationMs,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import {
|
||||
mcpServerPersonSchema,
|
||||
mcpServerSchema,
|
||||
type ListMcpServerToolCallsDto,
|
||||
type McpServerPerson,
|
||||
type McpServerToolCallResponse,
|
||||
type McpServerToolCallsResponse,
|
||||
} from '@n8n/api-types';
|
||||
import { isPerson, UserRepository } from '@n8n/db';
|
||||
import { Service } from '@n8n/di';
|
||||
|
||||
import type { McpServerToolCall } from '../database/entities/mcp-server-tool-call.entity';
|
||||
import { McpServerConnectionRepository } from '../database/repositories/mcp-server-connection.repository';
|
||||
import { McpServerToolCallRepository } from '../database/repositories/mcp-server-tool-call.repository';
|
||||
import { McpServerToolRepository } from '../database/repositories/mcp-server-tool.repository';
|
||||
import { McpServerRepository } from '../database/repositories/mcp-server.repository';
|
||||
import { McpServerNotFoundError } from '../errors/mcp-server-not-found.error';
|
||||
|
||||
// An id that is not a UUID cannot exist, and Postgres refuses it in a uuid column.
|
||||
const isServerId = (id: string) => mcpServerSchema.shape.id.safeParse(id).success;
|
||||
const isUserId = (id: string) => mcpServerPersonSchema.shape.userId.safeParse(id).success;
|
||||
|
||||
function personSortKey(person: McpServerPerson): string {
|
||||
return (
|
||||
[person.firstName, person.lastName].filter(Boolean).join(' ') ||
|
||||
person.email ||
|
||||
person.userId
|
||||
).toLowerCase();
|
||||
}
|
||||
|
||||
function unknownPerson(userId: string): McpServerPerson {
|
||||
return { userId, firstName: null, lastName: null, email: null };
|
||||
}
|
||||
|
||||
function toResponse(
|
||||
row: McpServerToolCall,
|
||||
people: Map<string, McpServerPerson>,
|
||||
): McpServerToolCallResponse {
|
||||
return {
|
||||
id: row.id,
|
||||
toolId: row.toolId,
|
||||
toolName: row.toolName,
|
||||
toolKind: row.toolKind,
|
||||
targetId: row.targetId,
|
||||
caller: row.userId ? (people.get(row.userId) ?? unknownPerson(row.userId)) : null,
|
||||
clientName: row.clientName,
|
||||
status: row.status,
|
||||
durationMs: row.durationMs,
|
||||
executionId: row.executionId,
|
||||
errorMessage: row.errorMessage,
|
||||
startedAt: row.startedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads the tool call log of a custom MCP server with filtering, sorting, and pagination. */
|
||||
@Service()
|
||||
export class McpServerToolCallsService {
|
||||
constructor(
|
||||
private readonly servers: McpServerRepository,
|
||||
private readonly tools: McpServerToolRepository,
|
||||
private readonly toolCalls: McpServerToolCallRepository,
|
||||
private readonly connections: McpServerConnectionRepository,
|
||||
private readonly users: UserRepository,
|
||||
) {}
|
||||
|
||||
async list(
|
||||
projectId: string,
|
||||
serverId: string,
|
||||
query: ListMcpServerToolCallsDto,
|
||||
): Promise<McpServerToolCallsResponse> {
|
||||
const server = isServerId(serverId)
|
||||
? await this.servers.findInProject(projectId, serverId)
|
||||
: null;
|
||||
if (!server) throw new McpServerNotFoundError();
|
||||
|
||||
const [{ items, total }, filterOptions, currentTools, connectedUserIds] = await Promise.all([
|
||||
this.toolCalls.listByServer(server.id, {
|
||||
toolName: query.toolName,
|
||||
userId: query.userId,
|
||||
status: query.status,
|
||||
startedAfter: query.startedAfter ? new Date(query.startedAfter) : undefined,
|
||||
startedBefore: query.startedBefore ? new Date(query.startedBefore) : undefined,
|
||||
sortBy: query.sortBy,
|
||||
sortDirection: query.sortDirection,
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
}),
|
||||
this.toolCalls.listFilterOptions(server.id),
|
||||
this.tools.listByServer(server.id),
|
||||
this.connections.listUserIdsByServer(server.id),
|
||||
]);
|
||||
|
||||
// Connection rows name every person who connected, also when their calls are older than
|
||||
// the window of recent calls that the filter options read.
|
||||
const pageUserIds = items.map((item) => item.userId).filter((id): id is string => id !== null);
|
||||
const allUserIds = [
|
||||
...new Set([...pageUserIds, ...filterOptions.userIds, ...connectedUserIds]),
|
||||
];
|
||||
const people = await this.people(allUserIds);
|
||||
|
||||
const toolNames = [
|
||||
...new Set([
|
||||
...filterOptions.toolNames,
|
||||
...items.map((item) => item.toolName),
|
||||
...currentTools.map((tool) => tool.toolName),
|
||||
]),
|
||||
].sort((a, b) => a.localeCompare(b));
|
||||
|
||||
const callers = allUserIds
|
||||
.map((userId) => people.get(userId) ?? unknownPerson(userId))
|
||||
.sort((a, b) => personSortKey(a).localeCompare(personSortKey(b)));
|
||||
|
||||
return {
|
||||
items: items.map((item) => toResponse(item, people)),
|
||||
total,
|
||||
filters: { tools: toolNames, callers },
|
||||
};
|
||||
}
|
||||
|
||||
private async people(userIds: string[]): Promise<Map<string, McpServerPerson>> {
|
||||
const ids = [...new Set(userIds)].filter(isUserId);
|
||||
if (ids.length === 0) return new Map();
|
||||
const users = (await this.users.findManyByIds(ids)).filter(isPerson);
|
||||
return new Map(
|
||||
users.map((user) => [
|
||||
user.id,
|
||||
{ userId: user.id, firstName: user.firstName, lastName: user.lastName, email: user.email },
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
// Fixtures for tests outside this package. They read, write, and clear the module tables here,
|
||||
// so integration tests never import entities or repositories directly.
|
||||
import type { McpServerToolDraftSource, McpServerToolKind } from '@n8n/api-types';
|
||||
import type {
|
||||
McpServerToolCallStatus,
|
||||
McpServerToolDraftSource,
|
||||
McpServerToolKind,
|
||||
} from '@n8n/api-types';
|
||||
import { Container } from '@n8n/di';
|
||||
|
||||
import { McpServerBlockRepository } from '../database/repositories/mcp-server-block.repository';
|
||||
@@ -8,6 +12,7 @@ import {
|
||||
McpServerConnectionRepository,
|
||||
type McpServerConnectionKey,
|
||||
} from '../database/repositories/mcp-server-connection.repository';
|
||||
import { McpServerToolCallRepository } from '../database/repositories/mcp-server-tool-call.repository';
|
||||
import { McpServerToolRepository } from '../database/repositories/mcp-server-tool.repository';
|
||||
import { McpServerRepository } from '../database/repositories/mcp-server.repository';
|
||||
|
||||
@@ -49,6 +54,22 @@ export type McpServerBlockFixture = {
|
||||
blockedAt?: Date;
|
||||
};
|
||||
|
||||
export type McpServerToolCallFixture = {
|
||||
serverId: string;
|
||||
toolId?: string | null;
|
||||
toolName: string;
|
||||
toolKind?: McpServerToolKind;
|
||||
targetId?: string | null;
|
||||
userId?: string | null;
|
||||
oauthClientId?: string | null;
|
||||
clientName: string;
|
||||
status: McpServerToolCallStatus;
|
||||
durationMs: number;
|
||||
executionId?: string | null;
|
||||
errorMessage?: string | null;
|
||||
startedAt?: Date;
|
||||
};
|
||||
|
||||
export type { McpServerConnectionKey };
|
||||
|
||||
/** Inserts a server row and reads it back. Omitted optional columns keep their database defaults. */
|
||||
@@ -111,8 +132,24 @@ export async function findMcpServerBlocks(serverId?: string) {
|
||||
return serverId ? await repo.listByServer(serverId) : await repo.findAll();
|
||||
}
|
||||
|
||||
/** Deletes every row from the four MCP server tables. */
|
||||
/** Inserts a tool call log row and reads it back. Omitted optional columns keep their defaults. */
|
||||
export async function createMcpServerToolCall(fixture: McpServerToolCallFixture) {
|
||||
return await Container.get(McpServerToolCallRepository).insertFixture(fixture);
|
||||
}
|
||||
|
||||
/** The repository of the tool call log, for tests that make its writes fail. */
|
||||
export function mcpServerToolCallRepository(): McpServerToolCallRepository {
|
||||
return Container.get(McpServerToolCallRepository);
|
||||
}
|
||||
|
||||
/** Lists all tool call log rows of one server, or every row across all servers. */
|
||||
export async function findMcpServerToolCalls(serverId?: string) {
|
||||
return await Container.get(McpServerToolCallRepository).findAll(serverId);
|
||||
}
|
||||
|
||||
/** Deletes every row from the five MCP server tables. */
|
||||
export async function clearMcpServerTables(): Promise<void> {
|
||||
await Container.get(McpServerToolCallRepository).deleteAll();
|
||||
await Container.get(McpServerConnectionRepository).deleteAll();
|
||||
await Container.get(McpServerBlockRepository).deleteAll();
|
||||
await Container.get(McpServerToolRepository).deleteAll();
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
getMcpServerPublicShare,
|
||||
getMcpServerShare,
|
||||
getToolDetail,
|
||||
listMcpServerToolCalls,
|
||||
} from '../mcp-servers.api';
|
||||
|
||||
const makeRestApiRequest = vi.hoisted(() => vi.fn());
|
||||
@@ -114,3 +115,30 @@ describe('tool draft request', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tool call log request', () => {
|
||||
it('sends only defined filter, sort, and pagination parameters', async () => {
|
||||
await listMcpServerToolCalls(context, 'project-1', 'server-1', {
|
||||
toolName: 'get_pipeline',
|
||||
status: 'error',
|
||||
sortBy: 'durationMs',
|
||||
sortDirection: 'asc',
|
||||
limit: 25,
|
||||
offset: 0,
|
||||
});
|
||||
|
||||
expect(makeRestApiRequest).toHaveBeenCalledWith(
|
||||
context,
|
||||
'GET',
|
||||
'/projects/project-1/mcp-servers/server-1/tool-calls',
|
||||
{
|
||||
toolName: 'get_pipeline',
|
||||
status: 'error',
|
||||
sortBy: 'durationMs',
|
||||
sortDirection: 'asc',
|
||||
limit: 25,
|
||||
offset: 0,
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { createComponentRenderer } from '@n8n/frontend-test-utils';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { screen } from '@testing-library/vue';
|
||||
|
||||
import { defaultToolCallFilters } from '../composables/useMcpServerToolCalls';
|
||||
import McpServerLogsFilter from './McpServerLogsFilter.vue';
|
||||
|
||||
const renderComponent = createComponentRenderer(McpServerLogsFilter);
|
||||
|
||||
describe('McpServerLogsFilter', () => {
|
||||
it.each([
|
||||
['Error', 'error'],
|
||||
['Unfinished', 'unfinished'],
|
||||
])('emits the status %s when it is picked', async (label, status) => {
|
||||
const { emitted } = renderComponent({
|
||||
props: {
|
||||
modelValue: defaultToolCallFilters(),
|
||||
activeCount: 0,
|
||||
tools: [],
|
||||
callers: [],
|
||||
},
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByTestId('mcp-server-logs-filter-trigger'));
|
||||
await userEvent.click(await screen.findByTestId('mcp-server-logs-filter-status'));
|
||||
await userEvent.click(await screen.findByRole('option', { name: label }));
|
||||
|
||||
expect(emitted('update:modelValue')).toEqual([[expect.objectContaining({ status })]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,271 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
mcpServerToolCallStatusSchema,
|
||||
type McpServerPerson,
|
||||
type McpServerToolCallStatus,
|
||||
} from '@n8n/api-types';
|
||||
import {
|
||||
N8nBadge,
|
||||
N8nButton,
|
||||
N8nInputLabel,
|
||||
N8nPopover,
|
||||
N8nSelect2,
|
||||
N8nText,
|
||||
} from '@n8n/design-system';
|
||||
import { useI18n } from '@n8n/i18n';
|
||||
import { computed, useId } from 'vue';
|
||||
|
||||
import type { McpServerToolCallFilterState } from '../composables/useMcpServerToolCalls';
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: McpServerToolCallFilterState;
|
||||
activeCount: number;
|
||||
tools: string[];
|
||||
callers: McpServerPerson[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: McpServerToolCallFilterState];
|
||||
reset: [];
|
||||
}>();
|
||||
|
||||
const i18n = useI18n();
|
||||
|
||||
const toolSelectId = useId();
|
||||
const personSelectId = useId();
|
||||
const statusSelectId = useId();
|
||||
const startDateId = useId();
|
||||
const endDateId = useId();
|
||||
|
||||
const hasFilters = computed(() => props.activeCount > 0);
|
||||
|
||||
function callerLabel(person: McpServerPerson): string {
|
||||
const name = [person.firstName, person.lastName].filter(Boolean).join(' ');
|
||||
if (name && person.email && person.email !== name) return `${name} (${person.email})`;
|
||||
return name || person.email || i18n.baseText('mcpServers.connections.unknownPerson');
|
||||
}
|
||||
|
||||
const toolOptions = computed(() => [
|
||||
{ value: 'all', label: i18n.baseText('mcpServers.logs.filter.allTools') },
|
||||
...props.tools.map((name) => ({ value: name, label: name })),
|
||||
]);
|
||||
|
||||
const personOptions = computed(() => [
|
||||
{ value: 'all', label: i18n.baseText('mcpServers.logs.filter.allPeople') },
|
||||
...props.callers.map((person) => ({ value: person.userId, label: callerLabel(person) })),
|
||||
]);
|
||||
|
||||
const statusOptions = computed(() => [
|
||||
{ value: 'all', label: i18n.baseText('mcpServers.logs.filter.anyStatus') },
|
||||
{ value: 'success', label: i18n.baseText('mcpServers.logs.status.success') },
|
||||
{ value: 'error', label: i18n.baseText('mcpServers.logs.status.error') },
|
||||
{ value: 'unfinished', label: i18n.baseText('mcpServers.logs.status.unfinished') },
|
||||
]);
|
||||
|
||||
function updateField<K extends keyof McpServerToolCallFilterState>(
|
||||
key: K,
|
||||
value: McpServerToolCallFilterState[K],
|
||||
) {
|
||||
emit('update:modelValue', { ...props.modelValue, [key]: value });
|
||||
}
|
||||
|
||||
function onToolChange(value: string | number | undefined) {
|
||||
if (typeof value === 'string') updateField('toolName', value);
|
||||
}
|
||||
|
||||
function onPersonChange(value: string | number | undefined) {
|
||||
if (typeof value === 'string') updateField('userId', value);
|
||||
}
|
||||
|
||||
function isStatusOption(value: unknown): value is 'all' | McpServerToolCallStatus {
|
||||
return value === 'all' || mcpServerToolCallStatusSchema.safeParse(value).success;
|
||||
}
|
||||
|
||||
function onStatusChange(value: string | number | undefined) {
|
||||
if (isStatusOption(value)) updateField('status', value);
|
||||
}
|
||||
|
||||
function onDateInput(key: 'startDate' | 'endDate', event: Event) {
|
||||
if (event.target instanceof HTMLInputElement) {
|
||||
updateField(key, event.target.value);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<N8nPopover width="360px" align="end" side="bottom" :content-class="$style.popoverContent">
|
||||
<template #trigger>
|
||||
<N8nButton
|
||||
variant="outline"
|
||||
size="small"
|
||||
icon="funnel"
|
||||
:active="hasFilters"
|
||||
:aria-label="i18n.baseText('mcpServers.logs.filter.button')"
|
||||
data-test-id="mcp-server-logs-filter-trigger"
|
||||
>
|
||||
<span>{{ i18n.baseText('mcpServers.logs.filter.button') }}</span>
|
||||
<N8nBadge
|
||||
v-if="hasFilters"
|
||||
variant="primary"
|
||||
size="xsmall"
|
||||
data-test-id="mcp-server-logs-filter-badge"
|
||||
>
|
||||
{{ activeCount }}
|
||||
</N8nBadge>
|
||||
</N8nButton>
|
||||
</template>
|
||||
<template #content>
|
||||
<div :class="$style.form" data-test-id="mcp-server-logs-filter-form">
|
||||
<div :class="$style.group">
|
||||
<N8nInputLabel
|
||||
:label="i18n.baseText('mcpServers.logs.filter.tool')"
|
||||
:input-name="toolSelectId"
|
||||
:bold="false"
|
||||
size="small"
|
||||
color="text-base"
|
||||
/>
|
||||
<N8nSelect2
|
||||
:id="toolSelectId"
|
||||
:model-value="modelValue.toolName"
|
||||
:items="toolOptions"
|
||||
size="small"
|
||||
data-test-id="mcp-server-logs-filter-tool"
|
||||
@update:model-value="onToolChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div :class="$style.group">
|
||||
<N8nInputLabel
|
||||
:label="i18n.baseText('mcpServers.logs.filter.person')"
|
||||
:input-name="personSelectId"
|
||||
:bold="false"
|
||||
size="small"
|
||||
color="text-base"
|
||||
/>
|
||||
<N8nSelect2
|
||||
:id="personSelectId"
|
||||
:model-value="modelValue.userId"
|
||||
:items="personOptions"
|
||||
size="small"
|
||||
data-test-id="mcp-server-logs-filter-person"
|
||||
@update:model-value="onPersonChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div :class="$style.group">
|
||||
<N8nInputLabel
|
||||
:label="i18n.baseText('mcpServers.logs.filter.status')"
|
||||
:input-name="statusSelectId"
|
||||
:bold="false"
|
||||
size="small"
|
||||
color="text-base"
|
||||
/>
|
||||
<N8nSelect2
|
||||
:id="statusSelectId"
|
||||
:model-value="modelValue.status"
|
||||
:items="statusOptions"
|
||||
size="small"
|
||||
data-test-id="mcp-server-logs-filter-status"
|
||||
@update:model-value="onStatusChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div :class="$style.group">
|
||||
<N8nInputLabel
|
||||
:label="i18n.baseText('mcpServers.logs.filter.dateRange')"
|
||||
:input-name="startDateId"
|
||||
:bold="false"
|
||||
size="small"
|
||||
color="text-base"
|
||||
/>
|
||||
<div :class="$style.dates">
|
||||
<!-- N8nInput does not support datetime-local inputs, so a native input is styled with input tokens. -->
|
||||
<input
|
||||
:id="startDateId"
|
||||
type="datetime-local"
|
||||
:value="modelValue.startDate"
|
||||
:aria-label="i18n.baseText('mcpServers.logs.filter.startDate')"
|
||||
:class="$style.dateInput"
|
||||
data-test-id="mcp-server-logs-filter-start-date"
|
||||
@input="onDateInput('startDate', $event)"
|
||||
/>
|
||||
<N8nText size="small" color="text-light" :class="$style.dateDivider">
|
||||
{{ i18n.baseText('mcpServers.logs.filter.to') }}
|
||||
</N8nText>
|
||||
<input
|
||||
:id="endDateId"
|
||||
type="datetime-local"
|
||||
:value="modelValue.endDate"
|
||||
:aria-label="i18n.baseText('mcpServers.logs.filter.endDate')"
|
||||
:class="$style.dateInput"
|
||||
data-test-id="mcp-server-logs-filter-end-date"
|
||||
@input="onDateInput('endDate', $event)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="hasFilters" :class="$style.footer">
|
||||
<N8nButton
|
||||
variant="ghost"
|
||||
size="small"
|
||||
:label="i18n.baseText('mcpServers.logs.filter.reset')"
|
||||
data-test-id="mcp-server-logs-filter-reset"
|
||||
@click="emit('reset')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</N8nPopover>
|
||||
</template>
|
||||
|
||||
<style lang="scss" module>
|
||||
@use '@n8n/design-system/css/mixins/focus';
|
||||
|
||||
.popoverContent {
|
||||
padding: var(--spacing--sm);
|
||||
}
|
||||
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing--sm);
|
||||
}
|
||||
|
||||
.group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing--4xs);
|
||||
}
|
||||
|
||||
.dates {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing--3xs);
|
||||
}
|
||||
|
||||
.dateDivider {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.dateInput {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-height: var(--spacing--xl);
|
||||
padding: var(--spacing--4xs) var(--spacing--2xs);
|
||||
border: var(--border);
|
||||
border-radius: var(--radius);
|
||||
background-color: var(--background--surface);
|
||||
color: var(--text-color);
|
||||
font-family: inherit;
|
||||
font-size: var(--font-size--2xs);
|
||||
|
||||
@include focus.focus-visible-ring;
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
padding-top: var(--spacing--3xs);
|
||||
border-top: var(--border);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,400 @@
|
||||
import type {
|
||||
McpServerResponse,
|
||||
McpServerToolCallResponse,
|
||||
McpServerToolCallsResponse,
|
||||
} from '@n8n/api-types';
|
||||
import { createComponentRenderer } from '@n8n/frontend-test-utils';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { fireEvent, screen, waitFor, within } from '@testing-library/vue';
|
||||
|
||||
import McpServerLogsTab from './McpServerLogsTab.vue';
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
listMcpServerToolCalls: vi.fn(),
|
||||
}));
|
||||
vi.mock('../mcp-servers.api', () => api);
|
||||
|
||||
const toast = vi.hoisted(() => ({ showError: vi.fn(), showMessage: vi.fn() }));
|
||||
vi.mock('@n8n/composables/useToast', () => ({ useToast: () => toast }));
|
||||
|
||||
vi.mock('vue-router', async (importOriginal) => ({
|
||||
...(await importOriginal()),
|
||||
useRouter: () => ({
|
||||
resolve: (location: { params?: { workflowId?: string; executionId?: string } }) => ({
|
||||
href: `/workflow/${location.params?.workflowId}/executions/${location.params?.executionId}`,
|
||||
}),
|
||||
}),
|
||||
}));
|
||||
|
||||
const server: McpServerResponse = {
|
||||
id: '0190a8d6-4a2e-7000-8000-000000000001',
|
||||
projectId: 'project-1',
|
||||
project: { name: 'Support', type: 'team' },
|
||||
name: 'Support desk',
|
||||
slug: 'support-desk',
|
||||
description: '',
|
||||
createdAt: '2026-11-24T10:00:00.000Z',
|
||||
updatedAt: '2026-11-24T10:00:00.000Z',
|
||||
};
|
||||
|
||||
const MAYA = {
|
||||
userId: '0190a8d6-4a2e-7000-8000-0000000000a1',
|
||||
firstName: 'Maya',
|
||||
lastName: 'Fischer',
|
||||
email: 'maya@acme.com',
|
||||
};
|
||||
|
||||
function makeCall(overrides: Partial<McpServerToolCallResponse> = {}): McpServerToolCallResponse {
|
||||
return {
|
||||
id: 1,
|
||||
toolId: '0190a8d6-4a2e-7000-8000-0000000000b1',
|
||||
toolName: 'get_pipeline',
|
||||
toolKind: 'workflow',
|
||||
targetId: 'wf-1',
|
||||
caller: MAYA,
|
||||
clientName: 'Claude Code',
|
||||
status: 'success',
|
||||
durationMs: 250,
|
||||
executionId: 'exec-123',
|
||||
errorMessage: null,
|
||||
startedAt: '2026-11-24T10:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeResponse(
|
||||
items: McpServerToolCallResponse[],
|
||||
overrides: Partial<McpServerToolCallsResponse> = {},
|
||||
): McpServerToolCallsResponse {
|
||||
return {
|
||||
items,
|
||||
total: items.length,
|
||||
filters: {
|
||||
tools: ['create_ticket', 'get_pipeline'],
|
||||
callers: [MAYA],
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const renderComponent = createComponentRenderer(McpServerLogsTab);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('McpServerLogsTab', () => {
|
||||
it('renders tool call rows with tool, person, client, status, duration, and View execution link', async () => {
|
||||
api.listMcpServerToolCalls.mockResolvedValue(
|
||||
makeResponse([
|
||||
makeCall({
|
||||
id: 2,
|
||||
toolName: 'get_pipeline',
|
||||
targetId: 'wf-1',
|
||||
executionId: 'exec-123',
|
||||
status: 'success',
|
||||
durationMs: 250,
|
||||
}),
|
||||
makeCall({
|
||||
id: 1,
|
||||
toolName: 'deleted_tool',
|
||||
caller: null,
|
||||
clientName: 'Cursor',
|
||||
status: 'error',
|
||||
durationMs: 1200,
|
||||
executionId: null,
|
||||
errorMessage: 'The workflow of this tool no longer exists.',
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
|
||||
const table = await screen.findByTestId('mcp-server-logs-table');
|
||||
const rows = within(table).getAllByRole('row');
|
||||
// Header row + 2 data rows
|
||||
expect(rows).toHaveLength(3);
|
||||
|
||||
const firstRow = within(rows[1]);
|
||||
expect(firstRow.getByText('get_pipeline')).toBeInTheDocument();
|
||||
expect(firstRow.getByText('Maya Fischer')).toBeInTheDocument();
|
||||
expect(firstRow.getByText('maya@acme.com')).toBeInTheDocument();
|
||||
expect(firstRow.getByText('Claude Code')).toBeInTheDocument();
|
||||
expect(firstRow.getByText('Succeeded')).toBeInTheDocument();
|
||||
const link = firstRow.getByTestId('mcp-server-log-view-execution');
|
||||
expect(link).toHaveAttribute('href', '/workflow/wf-1/executions/exec-123');
|
||||
|
||||
const secondRow = within(rows[2]);
|
||||
expect(secondRow.getByText('deleted_tool')).toBeInTheDocument();
|
||||
expect(secondRow.getByText('Unknown person')).toBeInTheDocument();
|
||||
expect(secondRow.getByText('Cursor')).toBeInTheDocument();
|
||||
expect(secondRow.getByText('Error')).toBeInTheDocument();
|
||||
expect(secondRow.queryByTestId('mcp-server-log-view-execution')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the empty state when no tool calls exist', async () => {
|
||||
api.listMcpServerToolCalls.mockResolvedValue(
|
||||
makeResponse([], { filters: { tools: [], callers: [] } }),
|
||||
);
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
|
||||
expect(await screen.findByTestId('mcp-server-logs-empty')).toHaveTextContent(
|
||||
'No tool calls yet',
|
||||
);
|
||||
});
|
||||
|
||||
it('offers a retry when loading fails', async () => {
|
||||
api.listMcpServerToolCalls.mockRejectedValueOnce(new Error('Network down'));
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
|
||||
const errorState = await screen.findByTestId('mcp-server-logs-load-error');
|
||||
expect(errorState).toHaveTextContent('Could not load the tool call log');
|
||||
expect(toast.showError).toHaveBeenCalled();
|
||||
|
||||
api.listMcpServerToolCalls.mockResolvedValueOnce(makeResponse([makeCall()]));
|
||||
await userEvent.click(within(errorState).getByRole('button', { name: 'Try again' }));
|
||||
|
||||
expect(await screen.findByTestId('mcp-server-logs-table')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('sorts when clicking a sortable column header', async () => {
|
||||
api.listMcpServerToolCalls.mockResolvedValue(makeResponse([makeCall()]));
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
await screen.findByTestId('mcp-server-logs-table');
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Run time' }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(api.listMcpServerToolCalls).toHaveBeenLastCalledWith(
|
||||
expect.anything(),
|
||||
server.projectId,
|
||||
server.id,
|
||||
expect.objectContaining({ sortBy: 'durationMs', sortDirection: 'desc', offset: 0 }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('filters by date range, shows active filter count, and resets filters from the empty state', async () => {
|
||||
api.listMcpServerToolCalls.mockResolvedValueOnce(makeResponse([makeCall()]));
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
await screen.findByTestId('mcp-server-logs-table');
|
||||
|
||||
await userEvent.click(screen.getByTestId('mcp-server-logs-filter-trigger'));
|
||||
const startInput = await screen.findByTestId('mcp-server-logs-filter-start-date');
|
||||
|
||||
api.listMcpServerToolCalls.mockResolvedValueOnce(makeResponse([]));
|
||||
await fireEvent.update(startInput, '2026-11-25T10:00');
|
||||
|
||||
await waitFor(() =>
|
||||
expect(api.listMcpServerToolCalls).toHaveBeenLastCalledWith(
|
||||
expect.anything(),
|
||||
server.projectId,
|
||||
server.id,
|
||||
expect.objectContaining({
|
||||
startedAfter: new Date('2026-11-25T10:00').toISOString(),
|
||||
offset: 0,
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(screen.getByTestId('mcp-server-logs-filter-badge')).toHaveTextContent('1');
|
||||
const emptyFiltered = await screen.findByTestId('mcp-server-logs-empty-filtered');
|
||||
expect(emptyFiltered).toHaveTextContent('No tool calls match your filters');
|
||||
|
||||
api.listMcpServerToolCalls.mockResolvedValueOnce(makeResponse([makeCall()]));
|
||||
await userEvent.click(within(emptyFiltered).getByRole('button', { name: 'Reset filters' }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(api.listMcpServerToolCalls).toHaveBeenLastCalledWith(
|
||||
expect.anything(),
|
||||
server.projectId,
|
||||
server.id,
|
||||
expect.objectContaining({ startedAfter: undefined }),
|
||||
),
|
||||
);
|
||||
expect(await screen.findByTestId('mcp-server-logs-table')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('toggles an already-descending column header to ascending on the first click', async () => {
|
||||
api.listMcpServerToolCalls.mockResolvedValue(makeResponse([makeCall()]));
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
await screen.findByTestId('mcp-server-logs-table');
|
||||
|
||||
// Initial sort is `startedAt: desc`. Clicking `Started` switches directly to `asc`.
|
||||
const startedButton = screen.getByRole('button', { name: 'Started' });
|
||||
expect(startedButton.closest('th')).toHaveAttribute('aria-sort', 'descending');
|
||||
await userEvent.click(startedButton);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(api.listMcpServerToolCalls).toHaveBeenLastCalledWith(
|
||||
expect.anything(),
|
||||
server.projectId,
|
||||
server.id,
|
||||
expect.objectContaining({ sortBy: 'startedAt', sortDirection: 'asc', offset: 0 }),
|
||||
),
|
||||
);
|
||||
expect(startedButton.closest('th')).toHaveAttribute('aria-sort', 'ascending');
|
||||
});
|
||||
|
||||
it('renders Reset filters in the filter popover as a keyboard-focusable button', async () => {
|
||||
api.listMcpServerToolCalls.mockResolvedValue(makeResponse([makeCall()]));
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
await screen.findByTestId('mcp-server-logs-table');
|
||||
|
||||
await userEvent.click(screen.getByTestId('mcp-server-logs-filter-trigger'));
|
||||
const startInput = await screen.findByTestId('mcp-server-logs-filter-start-date');
|
||||
await fireEvent.update(startInput, '2026-11-25T10:00');
|
||||
|
||||
const resetButton = await screen.findByTestId('mcp-server-logs-filter-reset');
|
||||
expect(resetButton.tagName).toBe('BUTTON');
|
||||
|
||||
await userEvent.click(resetButton);
|
||||
await waitFor(() =>
|
||||
expect(api.listMcpServerToolCalls).toHaveBeenLastCalledWith(
|
||||
expect.anything(),
|
||||
server.projectId,
|
||||
server.id,
|
||||
expect.objectContaining({ startedAfter: undefined }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('sets startedBefore to the end of the selected minute for endDate', async () => {
|
||||
api.listMcpServerToolCalls.mockResolvedValue(makeResponse([makeCall()]));
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
await screen.findByTestId('mcp-server-logs-table');
|
||||
|
||||
await userEvent.click(screen.getByTestId('mcp-server-logs-filter-trigger'));
|
||||
const endInput = await screen.findByTestId('mcp-server-logs-filter-end-date');
|
||||
|
||||
await fireEvent.update(endInput, '2026-11-25T10:30');
|
||||
|
||||
const expectedEnd = new Date('2026-11-25T10:30');
|
||||
expectedEnd.setSeconds(59, 999);
|
||||
await waitFor(() =>
|
||||
expect(api.listMcpServerToolCalls).toHaveBeenLastCalledWith(
|
||||
expect.anything(),
|
||||
server.projectId,
|
||||
server.id,
|
||||
expect.objectContaining({
|
||||
startedBefore: expectedEnd.toISOString(),
|
||||
offset: 0,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps filters and loaded rows when the server prop updates without changing its id', async () => {
|
||||
api.listMcpServerToolCalls.mockResolvedValue(makeResponse([makeCall()]));
|
||||
|
||||
const { rerender } = renderComponent({ props: { server } });
|
||||
await screen.findByTestId('mcp-server-logs-table');
|
||||
|
||||
await userEvent.click(screen.getByTestId('mcp-server-logs-filter-trigger'));
|
||||
const startInput = await screen.findByTestId('mcp-server-logs-filter-start-date');
|
||||
await fireEvent.update(startInput, '2026-11-25T10:00');
|
||||
await waitFor(() => expect(api.listMcpServerToolCalls).toHaveBeenCalledTimes(2));
|
||||
|
||||
await rerender({ server: { ...server, name: 'Renamed desk' } });
|
||||
|
||||
expect(api.listMcpServerToolCalls).toHaveBeenCalledTimes(2);
|
||||
expect(screen.getByTestId('mcp-server-logs-filter-badge')).toHaveTextContent('1');
|
||||
expect(screen.getByTestId('mcp-server-logs-table')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not overlap silent auto-refresh requests while a previous poll is still pending', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
||||
try {
|
||||
api.listMcpServerToolCalls.mockResolvedValueOnce(makeResponse([makeCall()]));
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
await screen.findByTestId('mcp-server-logs-table');
|
||||
|
||||
let resolvePoll!: (value: McpServerToolCallsResponse) => void;
|
||||
api.listMcpServerToolCalls.mockImplementationOnce(
|
||||
async () =>
|
||||
await new Promise<McpServerToolCallsResponse>((resolve) => {
|
||||
resolvePoll = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
await fireEvent.click(screen.getByTestId('mcp-server-logs-auto-refresh'));
|
||||
|
||||
// First interval starts one silent poll.
|
||||
await vi.advanceTimersByTimeAsync(4000);
|
||||
expect(api.listMcpServerToolCalls).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Subsequent ticks skip while that poll is still in flight.
|
||||
await vi.advanceTimersByTimeAsync(8000);
|
||||
expect(api.listMcpServerToolCalls).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Once the in-flight poll settles, the next tick starts a new poll.
|
||||
resolvePoll(makeResponse([makeCall()]));
|
||||
await Promise.resolve();
|
||||
api.listMcpServerToolCalls.mockResolvedValueOnce(makeResponse([makeCall()]));
|
||||
await vi.advanceTimersByTimeAsync(4000);
|
||||
expect(api.listMcpServerToolCalls).toHaveBeenCalledTimes(3);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('reloads when clicking the refresh button', async () => {
|
||||
api.listMcpServerToolCalls.mockResolvedValue(makeResponse([makeCall()]));
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
await screen.findByTestId('mcp-server-logs-table');
|
||||
|
||||
await userEvent.click(screen.getByTestId('mcp-server-logs-refresh'));
|
||||
|
||||
await waitFor(() => expect(api.listMcpServerToolCalls).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
it('shows the full tool name in a tooltip when hovering the tool cell', async () => {
|
||||
const longToolName = 'get_customer_pipeline_summary_by_owner_and_region';
|
||||
api.listMcpServerToolCalls.mockResolvedValue(
|
||||
makeResponse([makeCall({ toolName: longToolName })]),
|
||||
);
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
const toolCell = await screen.findByTestId('mcp-server-log-tool');
|
||||
await userEvent.hover(toolCell);
|
||||
|
||||
expect(await screen.findByTestId('tooltip-content')).toHaveTextContent(longToolName);
|
||||
});
|
||||
|
||||
it('shows the error message of a call as text, not as HTML', async () => {
|
||||
const errorMessage = 'Order failed. <a href="https://example.com">Open</a> <b>bold</b>';
|
||||
api.listMcpServerToolCalls.mockResolvedValue(
|
||||
makeResponse([makeCall({ status: 'error', executionId: null, errorMessage })]),
|
||||
);
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
await userEvent.hover(await screen.findByTestId('mcp-server-log-status'));
|
||||
|
||||
const tooltip = await screen.findByTestId('tooltip-content');
|
||||
expect(within(tooltip).getByTestId('mcp-server-log-error-message')).toHaveTextContent(
|
||||
errorMessage,
|
||||
);
|
||||
expect(tooltip.querySelector('a, b')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows a call whose run outlived the wait as Unfinished', async () => {
|
||||
api.listMcpServerToolCalls.mockResolvedValue(
|
||||
makeResponse([
|
||||
makeCall({ status: 'unfinished', errorMessage: 'The workflow is still running.' }),
|
||||
]),
|
||||
);
|
||||
|
||||
renderComponent({ props: { server } });
|
||||
|
||||
expect(await screen.findByTestId('mcp-server-log-status')).toHaveTextContent('Unfinished');
|
||||
expect(screen.getByTestId('mcp-server-log-view-execution')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,449 @@
|
||||
<script setup lang="ts">
|
||||
import type {
|
||||
McpServerPerson,
|
||||
McpServerResponse,
|
||||
McpServerToolCallResponse,
|
||||
McpServerToolCallSortBy,
|
||||
McpServerToolCallSortDirection,
|
||||
McpServerToolCallStatus,
|
||||
} from '@n8n/api-types';
|
||||
import {
|
||||
N8nAvatar,
|
||||
N8nBadge,
|
||||
N8nButton,
|
||||
N8nCheckbox,
|
||||
N8nEmptyState,
|
||||
N8nIcon,
|
||||
N8nLink,
|
||||
N8nLoading2,
|
||||
N8nSelect2,
|
||||
N8nText,
|
||||
N8nTimeAgo,
|
||||
N8nTooltip,
|
||||
} from '@n8n/design-system';
|
||||
import { N8nDataTableServer, type TableHeader, type TableOptions } from '@n8n/design-system/legacy';
|
||||
import { VIEWS } from '@n8n/frontend-constants/views';
|
||||
import { useI18n, type BaseTextKey } from '@n8n/i18n';
|
||||
import { computed } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { useMcpServerToolCalls } from '../composables/useMcpServerToolCalls';
|
||||
import McpServerLogsFilter from './McpServerLogsFilter.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
server: McpServerResponse;
|
||||
}>();
|
||||
|
||||
const i18n = useI18n();
|
||||
const router = useRouter();
|
||||
|
||||
const logs = useMcpServerToolCalls(
|
||||
() => props.server.projectId,
|
||||
() => props.server.id,
|
||||
);
|
||||
|
||||
type SortOptionKey =
|
||||
| 'startedAt:desc'
|
||||
| 'startedAt:asc'
|
||||
| 'durationMs:desc'
|
||||
| 'durationMs:asc'
|
||||
| 'toolName:asc'
|
||||
| 'toolName:desc'
|
||||
| 'status:asc'
|
||||
| 'status:desc';
|
||||
|
||||
const SORT_OPTION_MAP: Record<
|
||||
SortOptionKey,
|
||||
{ field: McpServerToolCallSortBy; direction: McpServerToolCallSortDirection }
|
||||
> = {
|
||||
'startedAt:desc': { field: 'startedAt', direction: 'desc' },
|
||||
'startedAt:asc': { field: 'startedAt', direction: 'asc' },
|
||||
'durationMs:desc': { field: 'durationMs', direction: 'desc' },
|
||||
'durationMs:asc': { field: 'durationMs', direction: 'asc' },
|
||||
'toolName:asc': { field: 'toolName', direction: 'asc' },
|
||||
'toolName:desc': { field: 'toolName', direction: 'desc' },
|
||||
'status:asc': { field: 'status', direction: 'asc' },
|
||||
'status:desc': { field: 'status', direction: 'desc' },
|
||||
};
|
||||
|
||||
const sortOptions = computed(() => [
|
||||
{ value: 'startedAt:desc', label: i18n.baseText('mcpServers.logs.sort.newest') },
|
||||
{ value: 'startedAt:asc', label: i18n.baseText('mcpServers.logs.sort.oldest') },
|
||||
{ value: 'durationMs:desc', label: i18n.baseText('mcpServers.logs.sort.longest') },
|
||||
{ value: 'durationMs:asc', label: i18n.baseText('mcpServers.logs.sort.shortest') },
|
||||
{ value: 'toolName:asc', label: i18n.baseText('mcpServers.logs.sort.toolAsc') },
|
||||
{ value: 'toolName:desc', label: i18n.baseText('mcpServers.logs.sort.toolDesc') },
|
||||
{ value: 'status:asc', label: i18n.baseText('mcpServers.logs.sort.statusAsc') },
|
||||
{ value: 'status:desc', label: i18n.baseText('mcpServers.logs.sort.statusDesc') },
|
||||
]);
|
||||
|
||||
const selectedSortKey = computed<SortOptionKey>(
|
||||
() => `${logs.sortBy.value}:${logs.sortDirection.value}`,
|
||||
);
|
||||
|
||||
const tableSortBy = computed(() => [
|
||||
{ id: logs.sortBy.value, desc: logs.sortDirection.value === 'desc' },
|
||||
]);
|
||||
|
||||
const STATUS_BADGES: Record<
|
||||
McpServerToolCallStatus,
|
||||
{ variant: 'success' | 'danger' | 'warning'; label: BaseTextKey }
|
||||
> = {
|
||||
success: { variant: 'success', label: 'mcpServers.logs.status.success' },
|
||||
error: { variant: 'danger', label: 'mcpServers.logs.status.error' },
|
||||
unfinished: { variant: 'warning', label: 'mcpServers.logs.status.unfinished' },
|
||||
};
|
||||
|
||||
const rows = computed(() => logs.data.value?.items ?? []);
|
||||
const total = computed(() => logs.data.value?.total ?? 0);
|
||||
const filterTools = computed(() => logs.data.value?.filters.tools ?? []);
|
||||
const filterCallers = computed(() => logs.data.value?.filters.callers ?? []);
|
||||
|
||||
const headers = computed<Array<TableHeader<McpServerToolCallResponse>>>(() => [
|
||||
{
|
||||
title: i18n.baseText('mcpServers.logs.column.tool'),
|
||||
key: 'toolName',
|
||||
width: 130,
|
||||
},
|
||||
{
|
||||
title: i18n.baseText('mcpServers.logs.column.person'),
|
||||
key: 'caller',
|
||||
disableSort: true,
|
||||
width: 150,
|
||||
},
|
||||
{
|
||||
title: i18n.baseText('mcpServers.logs.column.client'),
|
||||
key: 'clientName',
|
||||
disableSort: true,
|
||||
width: 100,
|
||||
},
|
||||
{
|
||||
title: i18n.baseText('mcpServers.logs.column.status'),
|
||||
key: 'status',
|
||||
width: 108,
|
||||
},
|
||||
{
|
||||
title: i18n.baseText('mcpServers.logs.column.startedAt'),
|
||||
key: 'startedAt',
|
||||
width: 102,
|
||||
},
|
||||
{
|
||||
title: i18n.baseText('mcpServers.logs.column.duration'),
|
||||
key: 'durationMs',
|
||||
width: 80,
|
||||
},
|
||||
{
|
||||
title: i18n.baseText('mcpServers.logs.column.execution'),
|
||||
key: 'executionId',
|
||||
disableSort: true,
|
||||
width: 120,
|
||||
},
|
||||
]);
|
||||
|
||||
const dateTimeFormat = new Intl.DateTimeFormat(undefined, {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'medium',
|
||||
});
|
||||
|
||||
function formatTimestamp(iso: string): string {
|
||||
const parsed = new Date(iso);
|
||||
return Number.isNaN(parsed.getTime()) ? iso : dateTimeFormat.format(parsed);
|
||||
}
|
||||
|
||||
function formatDuration(durationMs: number): string {
|
||||
return i18n.displayTimer(durationMs, true);
|
||||
}
|
||||
|
||||
function displayName(person: McpServerPerson | null): string {
|
||||
if (!person) return i18n.baseText('mcpServers.connections.unknownPerson');
|
||||
const name = [person.firstName, person.lastName].filter(Boolean).join(' ');
|
||||
return name || person.email || i18n.baseText('mcpServers.connections.unknownPerson');
|
||||
}
|
||||
|
||||
function executionHref(item: McpServerToolCallResponse): string | null {
|
||||
if (item.toolKind !== 'workflow' || !item.targetId || !item.executionId) return null;
|
||||
return router.resolve({
|
||||
name: VIEWS.EXECUTION_PREVIEW,
|
||||
params: { workflowId: item.targetId, executionId: item.executionId },
|
||||
}).href;
|
||||
}
|
||||
|
||||
function onSortSelect(value: string | number | undefined) {
|
||||
if (typeof value !== 'string' || !(value in SORT_OPTION_MAP)) return;
|
||||
const { field, direction } = SORT_OPTION_MAP[value as SortOptionKey];
|
||||
logs.setSort(field, direction);
|
||||
}
|
||||
|
||||
function isSortableField(id: string): id is McpServerToolCallSortBy {
|
||||
return id === 'startedAt' || id === 'durationMs' || id === 'toolName' || id === 'status';
|
||||
}
|
||||
|
||||
function onTableOptionsUpdate(options: TableOptions) {
|
||||
if (options.page !== logs.page.value || options.itemsPerPage !== logs.itemsPerPage.value) {
|
||||
logs.setPage(options.page, options.itemsPerPage);
|
||||
return;
|
||||
}
|
||||
const nextSort = options.sortBy[0];
|
||||
if (!nextSort) {
|
||||
// TanStack Table clears sort after `desc`; flip direction instead since the API always sorts.
|
||||
logs.setSort(logs.sortBy.value, logs.sortDirection.value === 'desc' ? 'asc' : 'desc');
|
||||
return;
|
||||
}
|
||||
if (isSortableField(nextSort.id)) {
|
||||
const nextDirection: McpServerToolCallSortDirection = nextSort.desc ? 'desc' : 'asc';
|
||||
if (nextSort.id !== logs.sortBy.value || nextDirection !== logs.sortDirection.value) {
|
||||
logs.setSort(nextSort.id, nextDirection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({ reload: () => logs.load() });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="$style.tab" data-test-id="mcp-server-logs">
|
||||
<div :class="$style.controls">
|
||||
<div :class="$style.controlsLeft">
|
||||
<N8nCheckbox
|
||||
v-model="logs.autoRefresh.value"
|
||||
:label="i18n.baseText('mcpServers.logs.autoRefresh')"
|
||||
data-test-id="mcp-server-logs-auto-refresh"
|
||||
/>
|
||||
<N8nButton
|
||||
variant="ghost"
|
||||
size="small"
|
||||
icon="refresh-cw"
|
||||
:label="i18n.baseText('mcpServers.logs.refresh')"
|
||||
:disabled="logs.loading.value"
|
||||
data-test-id="mcp-server-logs-refresh"
|
||||
@click="logs.load()"
|
||||
/>
|
||||
</div>
|
||||
<div :class="$style.controlsRight">
|
||||
<N8nSelect2
|
||||
:model-value="selectedSortKey"
|
||||
:items="sortOptions"
|
||||
size="small"
|
||||
menu-width="content"
|
||||
align="end"
|
||||
:aria-label="i18n.baseText('mcpServers.logs.sort.label')"
|
||||
:class="$style.sortSelect"
|
||||
data-test-id="mcp-server-logs-sort"
|
||||
@update:model-value="onSortSelect"
|
||||
/>
|
||||
<McpServerLogsFilter
|
||||
:model-value="logs.filters.value"
|
||||
:active-count="logs.activeFilterCount.value"
|
||||
:tools="filterTools"
|
||||
:callers="filterCallers"
|
||||
@update:model-value="logs.setFilters"
|
||||
@reset="logs.resetFilters"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<N8nLoading2 v-if="!logs.data.value && logs.loading.value" :rows="4" />
|
||||
<N8nEmptyState
|
||||
v-else-if="!logs.data.value && logs.loadFailed.value"
|
||||
:icon="{ type: 'icon', value: 'triangle-alert' }"
|
||||
:heading="i18n.baseText('mcpServers.logs.load.error')"
|
||||
:button-text="i18n.baseText('mcpServers.logs.load.retry')"
|
||||
data-test-id="mcp-server-logs-load-error"
|
||||
@click:button="logs.load()"
|
||||
/>
|
||||
<N8nEmptyState
|
||||
v-else-if="logs.data.value && total === 0 && logs.activeFilterCount.value === 0"
|
||||
:icon="{ type: 'icon', value: 'scroll-text' }"
|
||||
:heading="i18n.baseText('mcpServers.logs.empty.heading')"
|
||||
:description="i18n.baseText('mcpServers.logs.empty.description')"
|
||||
data-test-id="mcp-server-logs-empty"
|
||||
/>
|
||||
<N8nEmptyState
|
||||
v-else-if="logs.data.value && total === 0"
|
||||
:icon="{ type: 'icon', value: 'scroll-text' }"
|
||||
:heading="i18n.baseText('mcpServers.logs.empty.filtered.heading')"
|
||||
:description="i18n.baseText('mcpServers.logs.empty.filtered.description')"
|
||||
:button-text="i18n.baseText('mcpServers.logs.filter.reset')"
|
||||
data-test-id="mcp-server-logs-empty-filtered"
|
||||
@click:button="logs.resetFilters()"
|
||||
/>
|
||||
<N8nDataTableServer
|
||||
v-else-if="logs.data.value"
|
||||
:headers="headers"
|
||||
:items="rows"
|
||||
:items-length="total"
|
||||
:loading="logs.loading.value"
|
||||
:page="logs.page.value"
|
||||
:items-per-page="logs.itemsPerPage.value"
|
||||
:sort-by="tableSortBy"
|
||||
item-value="id"
|
||||
data-test-id="mcp-server-logs-table"
|
||||
@update:options="onTableOptionsUpdate"
|
||||
>
|
||||
<template #[`item.toolName`]="{ item }">
|
||||
<N8nTooltip as-child :content="item.toolName">
|
||||
<N8nText size="small" :class="$style.toolName" data-test-id="mcp-server-log-tool">
|
||||
{{ item.toolName }}
|
||||
</N8nText>
|
||||
</N8nTooltip>
|
||||
</template>
|
||||
<template #[`item.caller`]="{ item }">
|
||||
<div :class="$style.person" data-test-id="mcp-server-log-person">
|
||||
<N8nAvatar
|
||||
:first-name="item.caller?.firstName ?? undefined"
|
||||
:last-name="item.caller?.lastName ?? undefined"
|
||||
size="small"
|
||||
/>
|
||||
<div :class="$style.personText">
|
||||
<N8nText bold size="small" :class="$style.truncate">{{
|
||||
displayName(item.caller)
|
||||
}}</N8nText>
|
||||
<N8nText
|
||||
v-if="item.caller?.email && item.caller.email !== displayName(item.caller)"
|
||||
size="small"
|
||||
color="text-light"
|
||||
:class="$style.truncate"
|
||||
>
|
||||
{{ item.caller.email }}
|
||||
</N8nText>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template #[`item.clientName`]="{ item }">
|
||||
<N8nText size="small" data-test-id="mcp-server-log-client">
|
||||
{{ item.clientName }}
|
||||
</N8nText>
|
||||
</template>
|
||||
<template #[`item.status`]="{ item }">
|
||||
<N8nTooltip v-if="item.errorMessage" :content-class="$style.errorTooltip">
|
||||
<template #content>
|
||||
<!-- Caller text: the content slot renders it as text, the content prop as HTML. -->
|
||||
<span :class="$style.errorText" data-test-id="mcp-server-log-error-message">{{
|
||||
item.errorMessage
|
||||
}}</span>
|
||||
</template>
|
||||
<N8nBadge
|
||||
:variant="STATUS_BADGES[item.status].variant"
|
||||
size="small"
|
||||
data-test-id="mcp-server-log-status"
|
||||
>
|
||||
{{ i18n.baseText(STATUS_BADGES[item.status].label) }}
|
||||
</N8nBadge>
|
||||
</N8nTooltip>
|
||||
<N8nBadge
|
||||
v-else
|
||||
:variant="STATUS_BADGES[item.status].variant"
|
||||
size="small"
|
||||
data-test-id="mcp-server-log-status"
|
||||
>
|
||||
{{ i18n.baseText(STATUS_BADGES[item.status].label) }}
|
||||
</N8nBadge>
|
||||
</template>
|
||||
<template #[`item.startedAt`]="{ item }">
|
||||
<N8nTooltip :content="formatTimestamp(item.startedAt)">
|
||||
<N8nText size="small" data-test-id="mcp-server-log-started">
|
||||
<N8nTimeAgo :date="item.startedAt" capitalize />
|
||||
</N8nText>
|
||||
</N8nTooltip>
|
||||
</template>
|
||||
<template #[`item.durationMs`]="{ item }">
|
||||
<N8nText size="small" data-test-id="mcp-server-log-duration">
|
||||
{{ formatDuration(item.durationMs) }}
|
||||
</N8nText>
|
||||
</template>
|
||||
<template #[`item.executionId`]="{ item }">
|
||||
<N8nLink
|
||||
v-if="executionHref(item)"
|
||||
:to="executionHref(item)!"
|
||||
new-window
|
||||
size="small"
|
||||
:class="$style.executionLink"
|
||||
data-test-id="mcp-server-log-view-execution"
|
||||
data-attr="mcp-server-log-view-execution"
|
||||
>
|
||||
{{ i18n.baseText('mcpServers.logs.viewExecution') }}
|
||||
<N8nIcon icon="external-link" size="xsmall" />
|
||||
</N8nLink>
|
||||
<N8nText v-else size="small" color="text-light">–</N8nText>
|
||||
</template>
|
||||
</N8nDataTableServer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" module>
|
||||
.tab {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing--md);
|
||||
padding-top: var(--spacing--xs);
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--spacing--xs);
|
||||
}
|
||||
|
||||
.controlsLeft,
|
||||
.controlsRight {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing--xs);
|
||||
}
|
||||
|
||||
.sortSelect {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.toolName {
|
||||
display: block;
|
||||
font-family: var(--font-family--monospace);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.truncate {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.person {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing--2xs);
|
||||
min-width: 0;
|
||||
padding: var(--spacing--3xs) 0;
|
||||
}
|
||||
|
||||
.personText {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing--5xs);
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Error texts can have 2,000 characters: start at the top and scroll inside the tooltip. */
|
||||
.errorTooltip:global(.n8n-tooltip) {
|
||||
max-width: 320px;
|
||||
max-height: min(var(--reka-tooltip-content-available-height), 50vh);
|
||||
overflow-y: auto;
|
||||
justify-content: flex-start;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.errorText {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.executionLink {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing--4xs);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,87 @@
|
||||
import { effectScope } from 'vue';
|
||||
|
||||
import { defaultToolCallFilters, useMcpServerToolCalls } from './useMcpServerToolCalls';
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
listMcpServerToolCalls: vi.fn(),
|
||||
}));
|
||||
vi.mock('../mcp-servers.api', () => api);
|
||||
|
||||
const toast = vi.hoisted(() => ({ showError: vi.fn(), showMessage: vi.fn() }));
|
||||
vi.mock('@n8n/composables/useToast', () => ({ useToast: () => toast }));
|
||||
vi.mock('@n8n/stores/useRootStore', () => ({ useRootStore: () => ({ restApiContext: {} }) }));
|
||||
|
||||
const flushPromises = async () => await new Promise((resolve) => setTimeout(resolve));
|
||||
|
||||
const PROJECT_ID = 'project-1';
|
||||
const SERVER_ID = '0190a8d6-4a2e-7000-8000-000000000001';
|
||||
const USER_ID = '0190a8d6-4a2e-7000-8000-0000000000a1';
|
||||
|
||||
/** The query of the last list request. */
|
||||
function lastQuery() {
|
||||
const calls = api.listMcpServerToolCalls.mock.calls;
|
||||
return calls[calls.length - 1][3] as Record<string, unknown>;
|
||||
}
|
||||
|
||||
async function setup() {
|
||||
const scope = effectScope();
|
||||
const logs = scope.run(() => useMcpServerToolCalls(PROJECT_ID, SERVER_ID))!;
|
||||
onTestFinished(() => scope.stop());
|
||||
await flushPromises();
|
||||
return logs;
|
||||
}
|
||||
|
||||
describe('useMcpServerToolCalls', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
api.listMcpServerToolCalls.mockResolvedValue({
|
||||
items: [],
|
||||
total: 60,
|
||||
filters: { tools: [], callers: [] },
|
||||
});
|
||||
});
|
||||
|
||||
it('sends the offset of the page, and goes back to the first page when the page size changes', async () => {
|
||||
const logs = await setup();
|
||||
expect(lastQuery()).toEqual(expect.objectContaining({ limit: 25, offset: 0 }));
|
||||
|
||||
logs.setPage(1, 25);
|
||||
await flushPromises();
|
||||
expect(lastQuery()).toEqual(expect.objectContaining({ limit: 25, offset: 25 }));
|
||||
|
||||
logs.setPage(1, 50);
|
||||
await flushPromises();
|
||||
expect(logs.page.value).toBe(0);
|
||||
expect(lastQuery()).toEqual(expect.objectContaining({ limit: 50, offset: 0 }));
|
||||
});
|
||||
|
||||
it('sends the tool, person, and status filters, and none of them after a reset', async () => {
|
||||
const logs = await setup();
|
||||
logs.setPage(2, 25);
|
||||
await flushPromises();
|
||||
|
||||
logs.setFilters({
|
||||
...defaultToolCallFilters(),
|
||||
toolName: 'get_pipeline',
|
||||
userId: USER_ID,
|
||||
status: 'error',
|
||||
});
|
||||
await flushPromises();
|
||||
expect(lastQuery()).toEqual(
|
||||
expect.objectContaining({
|
||||
toolName: 'get_pipeline',
|
||||
userId: USER_ID,
|
||||
status: 'error',
|
||||
offset: 0,
|
||||
}),
|
||||
);
|
||||
expect(logs.activeFilterCount.value).toBe(3);
|
||||
|
||||
logs.resetFilters();
|
||||
await flushPromises();
|
||||
expect(lastQuery()).toEqual(
|
||||
expect.objectContaining({ toolName: undefined, userId: undefined, status: undefined }),
|
||||
);
|
||||
expect(logs.activeFilterCount.value).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
import {
|
||||
MCP_SERVER_TOOL_CALLS_DEFAULT_LIMIT,
|
||||
type McpServerToolCallSortBy,
|
||||
type McpServerToolCallSortDirection,
|
||||
type McpServerToolCallsResponse,
|
||||
type McpServerToolCallStatus,
|
||||
} from '@n8n/api-types';
|
||||
import { useLatestFetch } from '@n8n/composables/useLatestFetch';
|
||||
import { useToast } from '@n8n/composables/useToast';
|
||||
import { useI18n } from '@n8n/i18n';
|
||||
import { useRootStore } from '@n8n/stores/useRootStore';
|
||||
import { computed, onScopeDispose, ref, toValue, watch, type MaybeRefOrGetter } from 'vue';
|
||||
|
||||
import { listMcpServerToolCalls } from '../mcp-servers.api';
|
||||
|
||||
/** Refresh cadence when auto-refresh is enabled, matching the Executions list. */
|
||||
const AUTO_REFRESH_INTERVAL_MS = 4000;
|
||||
|
||||
export interface McpServerToolCallFilterState {
|
||||
toolName: string;
|
||||
userId: string;
|
||||
status: 'all' | McpServerToolCallStatus;
|
||||
/** Local datetime-local input value (`YYYY-MM-DDTHH:mm`), or empty. */
|
||||
startDate: string;
|
||||
/** Local datetime-local input value (`YYYY-MM-DDTHH:mm`), or empty. */
|
||||
endDate: string;
|
||||
}
|
||||
|
||||
export function defaultToolCallFilters(): McpServerToolCallFilterState {
|
||||
return {
|
||||
toolName: 'all',
|
||||
userId: 'all',
|
||||
status: 'all',
|
||||
startDate: '',
|
||||
endDate: '',
|
||||
};
|
||||
}
|
||||
|
||||
function toIsoDate(localValue: string, { endOfMinute = false } = {}): string | undefined {
|
||||
if (!localValue) return undefined;
|
||||
const parsed = new Date(localValue);
|
||||
if (Number.isNaN(parsed.getTime())) return undefined;
|
||||
// `datetime-local` values without seconds default to `:00.000`; include the full end minute.
|
||||
if (endOfMinute && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(localValue)) {
|
||||
parsed.setSeconds(59, 999);
|
||||
}
|
||||
return parsed.toISOString();
|
||||
}
|
||||
|
||||
export function useMcpServerToolCalls(
|
||||
projectId: MaybeRefOrGetter<string>,
|
||||
serverId: MaybeRefOrGetter<string>,
|
||||
) {
|
||||
const rootStore = useRootStore();
|
||||
const toast = useToast();
|
||||
const i18n = useI18n();
|
||||
const latestFetch = useLatestFetch();
|
||||
|
||||
const data = ref<McpServerToolCallsResponse | null>(null);
|
||||
const loading = ref(false);
|
||||
const loadFailed = ref(false);
|
||||
|
||||
const filters = ref<McpServerToolCallFilterState>(defaultToolCallFilters());
|
||||
const sortBy = ref<McpServerToolCallSortBy>('startedAt');
|
||||
const sortDirection = ref<McpServerToolCallSortDirection>('desc');
|
||||
const page = ref(0);
|
||||
const itemsPerPage = ref(MCP_SERVER_TOOL_CALLS_DEFAULT_LIMIT);
|
||||
const autoRefresh = ref(false);
|
||||
|
||||
let refreshTimer: ReturnType<typeof setInterval> | null = null;
|
||||
/** Counts in-flight loads, including silent polls, so auto-refresh ticks do not overlap. */
|
||||
let activeRequests = 0;
|
||||
|
||||
const activeFilterCount = computed(() => {
|
||||
const f = filters.value;
|
||||
return [
|
||||
f.toolName !== 'all',
|
||||
f.userId !== 'all',
|
||||
f.status !== 'all',
|
||||
Boolean(f.startDate),
|
||||
Boolean(f.endDate),
|
||||
].filter(Boolean).length;
|
||||
});
|
||||
|
||||
async function load({ silent = false } = {}) {
|
||||
const isLatest = latestFetch.next();
|
||||
activeRequests++;
|
||||
if (!silent) loading.value = true;
|
||||
loadFailed.value = false;
|
||||
try {
|
||||
const f = filters.value;
|
||||
const response = await listMcpServerToolCalls(
|
||||
rootStore.restApiContext,
|
||||
toValue(projectId),
|
||||
toValue(serverId),
|
||||
{
|
||||
toolName: f.toolName === 'all' ? undefined : f.toolName,
|
||||
userId: f.userId === 'all' ? undefined : f.userId,
|
||||
status: f.status === 'all' ? undefined : f.status,
|
||||
startedAfter: toIsoDate(f.startDate),
|
||||
startedBefore: toIsoDate(f.endDate, { endOfMinute: true }),
|
||||
sortBy: sortBy.value,
|
||||
sortDirection: sortDirection.value,
|
||||
limit: itemsPerPage.value,
|
||||
offset: page.value * itemsPerPage.value,
|
||||
},
|
||||
);
|
||||
if (isLatest()) data.value = response;
|
||||
} catch (error) {
|
||||
if (isLatest()) {
|
||||
loadFailed.value = true;
|
||||
if (!silent) toast.showError(error, i18n.baseText('mcpServers.logs.load.error'));
|
||||
}
|
||||
} finally {
|
||||
activeRequests = Math.max(0, activeRequests - 1);
|
||||
if (isLatest()) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function setFilters(next: McpServerToolCallFilterState) {
|
||||
filters.value = { ...next };
|
||||
page.value = 0;
|
||||
void load();
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
setFilters(defaultToolCallFilters());
|
||||
}
|
||||
|
||||
function setSort(field: McpServerToolCallSortBy, direction: McpServerToolCallSortDirection) {
|
||||
sortBy.value = field;
|
||||
sortDirection.value = direction;
|
||||
page.value = 0;
|
||||
void load();
|
||||
}
|
||||
|
||||
function setPage(nextPage: number, nextItemsPerPage: number) {
|
||||
const sizeChanged = nextItemsPerPage !== itemsPerPage.value;
|
||||
itemsPerPage.value = nextItemsPerPage;
|
||||
page.value = sizeChanged ? 0 : nextPage;
|
||||
void load();
|
||||
}
|
||||
|
||||
function stopAutoRefresh() {
|
||||
if (refreshTimer !== null) {
|
||||
clearInterval(refreshTimer);
|
||||
refreshTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
watch(autoRefresh, (enabled) => {
|
||||
stopAutoRefresh();
|
||||
if (enabled) {
|
||||
refreshTimer = setInterval(() => {
|
||||
if (activeRequests === 0) void load({ silent: true });
|
||||
}, AUTO_REFRESH_INTERVAL_MS);
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
[() => toValue(projectId), () => toValue(serverId)],
|
||||
() => {
|
||||
data.value = null;
|
||||
filters.value = defaultToolCallFilters();
|
||||
sortBy.value = 'startedAt';
|
||||
sortDirection.value = 'desc';
|
||||
page.value = 0;
|
||||
void load();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
onScopeDispose(stopAutoRefresh);
|
||||
|
||||
return {
|
||||
data,
|
||||
loading,
|
||||
loadFailed,
|
||||
filters,
|
||||
activeFilterCount,
|
||||
sortBy,
|
||||
sortDirection,
|
||||
page,
|
||||
itemsPerPage,
|
||||
autoRefresh,
|
||||
load,
|
||||
setFilters,
|
||||
resetFilters,
|
||||
setSort,
|
||||
setPage,
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
AddMcpServerNodeToolDto,
|
||||
CreateMcpServerDto,
|
||||
DraftMcpServerAgentToolDto,
|
||||
McpServerAgentToolCandidate,
|
||||
McpServerBlockResponse,
|
||||
McpServerConnectionsResponse,
|
||||
McpServerDetailResponse,
|
||||
@@ -11,7 +12,10 @@ import type {
|
||||
McpServerShare,
|
||||
McpServerSharePublic,
|
||||
McpServerSlugAvailability,
|
||||
McpServerAgentToolCandidate,
|
||||
McpServerToolCallSortBy,
|
||||
McpServerToolCallSortDirection,
|
||||
McpServerToolCallsResponse,
|
||||
McpServerToolCallStatus,
|
||||
McpServerToolCandidate,
|
||||
McpServerToolDetailResponse,
|
||||
McpServerToolDraftField,
|
||||
@@ -338,3 +342,40 @@ export async function removeMcpServerUser(
|
||||
`${serverPath(projectId, serverId)}/connections/${userId}`,
|
||||
);
|
||||
}
|
||||
|
||||
export interface ListMcpServerToolCallsParams {
|
||||
toolName?: string;
|
||||
userId?: string;
|
||||
status?: McpServerToolCallStatus;
|
||||
startedAfter?: string;
|
||||
startedBefore?: string;
|
||||
sortBy?: McpServerToolCallSortBy;
|
||||
sortDirection?: McpServerToolCallSortDirection;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
/** Logged tool calls of a server, with optional filtering, sorting, and pagination. */
|
||||
export async function listMcpServerToolCalls(
|
||||
context: IRestApiContext,
|
||||
projectId: string,
|
||||
serverId: string,
|
||||
params: ListMcpServerToolCallsParams = {},
|
||||
): Promise<McpServerToolCallsResponse> {
|
||||
const query: Record<string, string | number> = {};
|
||||
if (params.toolName) query.toolName = params.toolName;
|
||||
if (params.userId) query.userId = params.userId;
|
||||
if (params.status) query.status = params.status;
|
||||
if (params.startedAfter) query.startedAfter = params.startedAfter;
|
||||
if (params.startedBefore) query.startedBefore = params.startedBefore;
|
||||
if (params.sortBy) query.sortBy = params.sortBy;
|
||||
if (params.sortDirection) query.sortDirection = params.sortDirection;
|
||||
if (params.limit !== undefined) query.limit = params.limit;
|
||||
if (params.offset !== undefined) query.offset = params.offset;
|
||||
return await makeRestApiRequest(
|
||||
context,
|
||||
'GET',
|
||||
`${serverPath(projectId, serverId)}/tool-calls`,
|
||||
query,
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ export const MCP_SERVERS_LIST_VIEW = 'McpServersListView';
|
||||
export const PROJECT_MCP_SERVERS = 'ProjectMcpServers';
|
||||
export const MCP_SERVER_VIEW = 'McpServerView';
|
||||
export const MCP_SERVER_CONNECTIONS_VIEW = 'McpServerConnectionsView';
|
||||
export const MCP_SERVER_LOGS_VIEW = 'McpServerLogsView';
|
||||
export const MCP_SERVER_SHARE_VIEW = 'McpServerShareView';
|
||||
|
||||
/** The share page of a server is `<editor>/mcp-share/<slug>`. Anyone with the link can open it. */
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createMemoryHistory, createRouter, type RouteRecordRaw } from 'vue-rout
|
||||
|
||||
import {
|
||||
MCP_SERVER_CONNECTIONS_VIEW,
|
||||
MCP_SERVER_LOGS_VIEW,
|
||||
MCP_SERVER_SHARE_VIEW,
|
||||
MCP_SERVER_VIEW,
|
||||
MCP_SERVERS_LIST_VIEW,
|
||||
@@ -41,6 +42,7 @@ function createTestRouter() {
|
||||
route(PROJECT_MCP_SERVERS),
|
||||
route(MCP_SERVER_VIEW),
|
||||
route(MCP_SERVER_CONNECTIONS_VIEW),
|
||||
route(MCP_SERVER_LOGS_VIEW),
|
||||
...redirectRoutes,
|
||||
{ path: 'workflows', name: VIEWS.PROJECTS_WORKFLOWS, component: stub },
|
||||
],
|
||||
@@ -156,6 +158,7 @@ describe('McpServersModule', () => {
|
||||
it.each([
|
||||
['/projects/project-1/mcp-servers/server-1', MCP_SERVER_VIEW],
|
||||
['/projects/project-1/mcp-servers/server-1/access', MCP_SERVER_CONNECTIONS_VIEW],
|
||||
['/projects/project-1/mcp-servers/server-1/logs', MCP_SERVER_LOGS_VIEW],
|
||||
])('opens %s for a person who can read servers', async (path, name) => {
|
||||
setUp({ scopes: ['mcpServer:read'] });
|
||||
const router = createTestRouter();
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { NavigationGuard } from 'vue-router';
|
||||
|
||||
import {
|
||||
MCP_SERVER_CONNECTIONS_VIEW,
|
||||
MCP_SERVER_LOGS_VIEW,
|
||||
MCP_SERVER_SHARE_PATH,
|
||||
MCP_SERVER_SHARE_VIEW,
|
||||
MCP_SERVER_VIEW,
|
||||
@@ -66,6 +67,13 @@ export const McpServersModule = defineFrontendModule({
|
||||
meta: { projectRoute: true, middleware: ['authenticated', 'custom'] },
|
||||
beforeEnter: guardProjectRoute('canRead'),
|
||||
},
|
||||
{
|
||||
name: MCP_SERVER_LOGS_VIEW,
|
||||
path: 'mcp-servers/:serverId/logs',
|
||||
component: McpServerView,
|
||||
meta: { projectRoute: true, middleware: ['authenticated', 'custom'] },
|
||||
beforeEnter: guardProjectRoute('canRead'),
|
||||
},
|
||||
{
|
||||
// Old links from before the tab rename go to `/access`.
|
||||
path: 'mcp-servers/:serverId/connections',
|
||||
|
||||
@@ -10,6 +10,7 @@ import { computed, defineComponent } from 'vue';
|
||||
|
||||
import {
|
||||
MCP_SERVER_CONNECTIONS_VIEW,
|
||||
MCP_SERVER_LOGS_VIEW,
|
||||
MCP_SERVER_VIEW,
|
||||
MCP_SERVERS_LIST_VIEW,
|
||||
} from '../mcp-servers.constants';
|
||||
@@ -20,6 +21,7 @@ const api = vi.hoisted(() => ({
|
||||
updateMcpServer: vi.fn(),
|
||||
deleteMcpServer: vi.fn(),
|
||||
listMcpServerConnections: vi.fn(),
|
||||
listMcpServerToolCalls: vi.fn(),
|
||||
checkMcpServerSlug: vi.fn(),
|
||||
}));
|
||||
vi.mock('../mcp-servers.api', () => api);
|
||||
@@ -148,6 +150,11 @@ describe('McpServerView', () => {
|
||||
}));
|
||||
api.deleteMcpServer.mockResolvedValue(undefined);
|
||||
api.listMcpServerConnections.mockResolvedValue({ connections: [], blocks: [] });
|
||||
api.listMcpServerToolCalls.mockResolvedValue({
|
||||
items: [],
|
||||
total: 0,
|
||||
filters: { tools: [], callers: [] },
|
||||
});
|
||||
api.checkMcpServerSlug.mockResolvedValue({ available: true, reason: null });
|
||||
});
|
||||
|
||||
@@ -304,7 +311,7 @@ describe('McpServerView', () => {
|
||||
expect(screen.queryByTestId('stub-build')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('switches between Build and Access locally without changing the route', async () => {
|
||||
it('switches between Build, Access, and Logs locally without changing the route', async () => {
|
||||
provideAssistant();
|
||||
await renderArtifact();
|
||||
|
||||
@@ -315,6 +322,10 @@ describe('McpServerView', () => {
|
||||
expect(screen.queryByTestId('mcp-server-contents')).not.toBeInTheDocument();
|
||||
expect(push).not.toHaveBeenCalled();
|
||||
|
||||
await userEvent.click(screen.getByText('Logs'));
|
||||
expect(screen.getByTestId('mcp-server-logs')).toBeInTheDocument();
|
||||
expect(push).not.toHaveBeenCalled();
|
||||
|
||||
await userEvent.click(screen.getByText('Build'));
|
||||
expect(screen.getByTestId('mcp-server-contents')).toBeInTheDocument();
|
||||
});
|
||||
@@ -403,13 +414,23 @@ describe('McpServerView', () => {
|
||||
});
|
||||
|
||||
describe('tabs', () => {
|
||||
it('shows the tabs "Build" and "Access", with "Build" open', async () => {
|
||||
it('shows the tabs "Build", "Access", and "Logs", with "Build" open', async () => {
|
||||
await renderPage();
|
||||
|
||||
expect(screen.getByText('Build')).toBeInTheDocument();
|
||||
expect(await screen.findByText('Access 0')).toBeInTheDocument();
|
||||
expect(screen.getByText('Logs')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('mcp-server-contents')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('mcp-server-connections')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('mcp-server-logs')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens the logs on their own route', async () => {
|
||||
route.name = MCP_SERVER_LOGS_VIEW;
|
||||
await renderPage();
|
||||
|
||||
expect(screen.getByTestId('mcp-server-logs')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('mcp-server-contents')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens the Connect modal from the empty Access tab', async () => {
|
||||
|
||||
@@ -27,6 +27,7 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import McpServerConnectModal from '../components/McpServerConnectModal.vue';
|
||||
import McpServerConnectionsTab from '../components/McpServerConnectionsTab.vue';
|
||||
import McpServerContentsTab from '../components/McpServerContentsTab.vue';
|
||||
import McpServerLogsTab from '../components/McpServerLogsTab.vue';
|
||||
import RenameMcpServerDialog from '../components/RenameMcpServerDialog.vue';
|
||||
import { useMcpServerConnections } from '../composables/useMcpServerConnections';
|
||||
import { useMcpServerUrl } from '../composables/useMcpServerUrl';
|
||||
@@ -38,6 +39,7 @@ import {
|
||||
} from '../mcp-servers.api';
|
||||
import {
|
||||
MCP_SERVER_CONNECTIONS_VIEW,
|
||||
MCP_SERVER_LOGS_VIEW,
|
||||
MCP_SERVER_VIEW,
|
||||
MCP_SERVERS_LIST_VIEW,
|
||||
} from '../mcp-servers.constants';
|
||||
@@ -134,11 +136,14 @@ const tabs = computed(() => [
|
||||
interpolate: { count: String(connections.rowCount.value) },
|
||||
}),
|
||||
},
|
||||
{ value: MCP_SERVER_LOGS_VIEW, label: i18n.baseText('mcpServers.server.tabs.logs') },
|
||||
]);
|
||||
|
||||
const selectedTab = computed(() => {
|
||||
if (props.artifactMode) return localTab.value;
|
||||
return route.name === MCP_SERVER_CONNECTIONS_VIEW ? MCP_SERVER_CONNECTIONS_VIEW : MCP_SERVER_VIEW;
|
||||
if (route.name === MCP_SERVER_CONNECTIONS_VIEW) return MCP_SERVER_CONNECTIONS_VIEW;
|
||||
if (route.name === MCP_SERVER_LOGS_VIEW) return MCP_SERVER_LOGS_VIEW;
|
||||
return MCP_SERVER_VIEW;
|
||||
});
|
||||
|
||||
const breadcrumbs = computed<PathItem[]>(() => [
|
||||
@@ -546,7 +551,7 @@ defineExpose({ refresh });
|
||||
@tools-changed="shareableToolCount = $event"
|
||||
/>
|
||||
<McpServerConnectionsTab
|
||||
v-else
|
||||
v-else-if="selectedTab === MCP_SERVER_CONNECTIONS_VIEW"
|
||||
:server="server"
|
||||
:connections="connections.data.value"
|
||||
:loading="connections.loading.value"
|
||||
@@ -555,6 +560,7 @@ defineExpose({ refresh });
|
||||
@changed="connections.load"
|
||||
@connect="connectOpen = true"
|
||||
/>
|
||||
<McpServerLogsTab v-else :server="server" />
|
||||
</div>
|
||||
|
||||
<McpServerConnectModal v-model:open="connectOpen" :server="server" />
|
||||
|
||||
Reference in new issue
Block a user