Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(chat): long chats keep their tools (#16393)

Hazem Adel0fc01d44e3f7
diff --git a/brain/knowledge/flows-execution/chat.md b/brain/knowledge/flows-execution/chat.md
index 33322e16b15..fdda0b48d11 100644
--- a/brain/knowledge/flows-execution/chat.md
+++ b/brain/knowledge/flows-execution/chat.md
@@ -68,6 +68,8 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-
- **On a saved-agent run, choosing a different account in the connection card does nothing.** `onConnectionSelected` writes into `selectedConnectionByPiece` (`execute-agent-run.ts`), which is read only through `getSelectedAuth`, passed only to the MCP tool set — and `AgentRunSource.AGENT` is not granted `groups.mcp` at all. Configured piece tools carry the agent's stored `pieceMetadata` auth instead. So the card reports the account as connected while the tool keeps calling on the pinned one. Only the in-place Reconnect actually repairs an agent run, because it re-authorizes the same connection row the agent is pinned to. So `/v1/agents/conversations/:id/connections` answers `{ connections, reconnectOnly }`, and for an `AGENT`-source conversation returns only the accounts that agent's tools pin. Three things that branch has to get right, each of which was a live bug first: match on `(projectId, externalId)`, because `externalId` is caller-supplied and its index is **not** unique, so a same-id row in another project can pose as the pinned one; read the pin through `published ?? draft`, the same as the run; and unwrap the pre-0.87 `{{connections['id']}}` template form, or an older agent reads as having no pinned account and the card tells the user their live account is gone. The card must also carry the row's own `projectId` into the reconnect dialog, which otherwise falls back to the session project and repairs the wrong one.
+- **The chat's internal MCP token lives as long as a turn can (2 hours), not 15 minutes.** It's issued once per turn by `issueChatTurnAccessToken` (called from `agentMcp.getCredentials`) and kept in worker memory. `issueInternalAccessToken`, which the `/mcp-server/token` route hands to callers, keeps 15 minutes. With the 15-minute outside-client lifetime, any turn that waited on a card long enough lost every `ap_*` tool with "authentication failed" and stopped half done. Outside MCP clients keep their 15-minute tokens.
+
### Key files
Entry point: `agentModule`, the Fastify plugin registered in `packages/server/api/src/app/app.ts`.
diff --git a/packages/server/api/src/app/ee/agent/mcp/agent-mcp.ts b/packages/server/api/src/app/ee/agent/mcp/agent-mcp.ts
index aaf0c78da17..b9fb53b46bd 100644
--- a/packages/server/api/src/app/ee/agent/mcp/agent-mcp.ts
+++ b/packages/server/api/src/app/ee/agent/mcp/agent-mcp.ts
@@ -12,7 +12,7 @@ async function getMcpCredentials({ platformId, userId, log }: {
log: FastifyBaseLogger
}): Promise<McpCredentials> {
const { data: accessToken, error } = await tryCatch(() =>
- mcpOAuthTokenService.issueInternalAccessToken({ userId, platformId, projectId: null }),
+ mcpOAuthTokenService.issueChatTurnAccessToken({ userId, platformId, projectId: null }),
)
if (error) {
log.warn({ error, platform: { id: platformId } }, 'Failed to get MCP credentials — chat will work without MCP tools')
diff --git a/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token-lifetimes.ts b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token-lifetimes.ts
index 9fe49c5b716..29ad4761336 100644
--- a/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token-lifetimes.ts
+++ b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token-lifetimes.ts
@@ -1,6 +1,9 @@
+import { MAX_AGENT_TURN_WALL_CLOCK_MS } from '@activepieces/shared'
+
const CLOCK_SKEW_BUFFER_SECONDS = 60
export const MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS = 15 * 60
export const MCP_OAUTH_REFRESH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000
export const MCP_OAUTH_ID_TOKEN_TTL_SECONDS = 60 * 60
export const MCP_OAUTH_REVOKED_GRANT_TTL_SECONDS = MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS + CLOCK_SKEW_BUFFER_SECONDS
+export const MCP_CHAT_TURN_ACCESS_TOKEN_TTL_SECONDS = MAX_AGENT_TURN_WALL_CLOCK_MS / 1000
diff --git a/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.service.ts b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.service.ts
index ce6d94b3174..b9843d7d32f 100644
--- a/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.service.ts
+++ b/packages/server/api/src/app/mcp/oauth/token/mcp-oauth-token.service.ts
@@ -14,7 +14,7 @@ import { McpOAuthClientEntity } from '../client/mcp-oauth-client.entity'
import { DEFAULT_MCP_OAUTH_SCOPES } from '../mcp-oauth-scopes'
import { mcpOAuthPkce } from '../mcp-oauth.pkce'
import { mcpOAuthRevocationList } from './mcp-oauth-revocation-list'
-import { MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS, MCP_OAUTH_REFRESH_TOKEN_TTL_MS } from './mcp-oauth-token-lifetimes'
+import { MCP_CHAT_TURN_ACCESS_TOKEN_TTL_SECONDS, MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS, MCP_OAUTH_REFRESH_TOKEN_TTL_MS } from './mcp-oauth-token-lifetimes'
import { McpOAuthTokenEntity } from './mcp-oauth-token.entity'
const repo = repoFactory(McpOAuthTokenEntity)
@@ -46,7 +46,7 @@ async function issueAccessToken(params: IssueAccessTokenParams): Promise<string>
type: 'mcp_oauth',
},
key,
- expiresInSeconds: MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,
+ expiresInSeconds: params.expiresInSeconds,
audience: JwtAudience.MCP_OAUTH_ACCESS,
})
}
@@ -87,6 +87,7 @@ export const mcpOAuthTokenService = {
grantId: tokenRecord.id,
clientKey,
scopes: params.scopes,
+ expiresInSeconds: MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,
})
return {
@@ -121,6 +122,7 @@ export const mcpOAuthTokenService = {
grantId: record.id,
clientKey,
scopes: record.scopes ?? [],
+ expiresInSeconds: MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS,
})
return {
@@ -229,9 +231,16 @@ export const mcpOAuthTokenService = {
await mcpOAuthRevocationList.revoke({ grantIds })
},
- async issueInternalAccessToken({ userId, platformId, projectId }: { userId: string, platformId: string, projectId: string | null }): Promise<string> {
- return issueAccessToken({ userId, platformId, projectId, clientId: INTERNAL_CHAT_CLIENT_ID, grantId: null, clientKey: null, scopes: DEFAULT_MCP_OAUTH_SCOPES })
+ async issueInternalAccessToken(params: InternalTokenParams): Promise<string> {
+ return issueInternalToken({ ...params, expiresInSeconds: MCP_OAUTH_ACCESS_TOKEN_TTL_SECONDS })
},
+ async issueChatTurnAccessToken(params: InternalTokenParams): Promise<string> {
+ return issueInternalToken({ ...params, expiresInSeconds: MCP_CHAT_TURN_ACCESS_TOKEN_TTL_SECONDS })
+ },
+}
+
+async function issueInternalToken({ userId, platformId, projectId, expiresInSeconds }: InternalTokenParams & { expiresInSeconds: number }): Promise<string> {
+ return issueAccessToken({ userId, platformId, projectId, clientId: INTERNAL_CHAT_CLIENT_ID, grantId: null, clientKey: null, scopes: DEFAULT_MCP_OAUTH_SCOPES, expiresInSeconds })
}
function applyGrantScope<T extends ObjectLiteral>(queryBuilder: SelectQueryBuilder<T>, { platformId, userId }: GrantScope): void {
@@ -262,6 +271,12 @@ export class OAuthTokenError extends Error {
}
}
+type InternalTokenParams = {
+ userId: string
+ platformId: string
+ projectId: string | null
+}
+
type IssueAccessTokenParams = {
userId: string
projectId: string | null
@@ -270,6 +285,7 @@ type IssueAccessTokenParams = {
grantId: string | null
clientKey: McpOAuthClientKey | null
scopes: string[]
+ expiresInSeconds: number
}
type ExchangeCodeParams = {
diff --git a/packages/server/api/test/integration/cloud/mcp/mcp-in-app-chat-access.test.ts b/packages/server/api/test/integration/cloud/mcp/mcp-in-app-chat-access.test.ts
index 45dcc2e42f6..4cfa667fa96 100644
--- a/packages/server/api/test/integration/cloud/mcp/mcp-in-app-chat-access.test.ts
+++ b/packages/server/api/test/integration/cloud/mcp/mcp-in-app-chat-access.test.ts
@@ -1,7 +1,7 @@
import { apId, Permission, RoleType } from '@activepieces/core-utils'
import { FastifyInstance } from 'fastify'
import { StatusCodes } from 'http-status-codes'
-import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { mcpOAuthTokenService } from '../../../../src/app/mcp/oauth/token/mcp-oauth-token.service'
import { db } from '../../../helpers/db'
import { McpClient, mcpClientHelpers } from '../../../helpers/mcp-client'
@@ -41,7 +41,7 @@ async function startConversation({ ctx, projectId }: { ctx: TestContext, project
}
async function chatClient({ ctx, conversationId }: { ctx: TestContext, conversationId: string }): Promise<McpClient> {
- const accessToken = await mcpOAuthTokenService.issueInternalAccessToken({ userId: ctx.user.id, platformId: ctx.platform.id, projectId: null })
+ const accessToken = await mcpOAuthTokenService.issueChatTurnAccessToken({ userId: ctx.user.id, platformId: ctx.platform.id, projectId: null })
return { accessToken, endpoint: '/mcp/platform', conversationId }
}
@@ -66,6 +66,29 @@ describe('In-app AI Chat on the MCP server', () => {
expect(text).toContain(Permission.WRITE_FLOW)
})
+ it('keeps the chat token working for a turn that runs longer than an outside client token lasts', async () => {
+ const { owner, member } = await setup({ permissions: [Permission.READ_FLOW] })
+ const conversationId = await startConversation({ ctx: member, projectId: owner.project.id })
+ const mcpClient = await chatClient({ ctx: member, conversationId })
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(Date.now() + LONG_TURN_MS)
+
+ const text = await mcpClientHelpers.callTool({ app, mcpClient, name: 'ap_list_flows' }).finally(() => vi.useRealTimers())
+
+ expect(text).toContain('✅')
+ })
+
+ it('keeps the 15-minute lifetime on a token from the /token route', async () => {
+ const { owner } = await setup({ permissions: [Permission.READ_FLOW] })
+ const accessToken = await mcpOAuthTokenService.issueInternalAccessToken({ userId: owner.user.id, platformId: owner.platform.id, projectId: owner.project.id })
+ vi.useFakeTimers({ toFake: ['Date'] })
+ vi.setSystemTime(Date.now() + LONG_TURN_MS)
+
+ const text = await mcpClientHelpers.callTool({ app, mcpClient: { accessToken, endpoint: '/mcp' }, name: 'ap_list_flows' }).catch((error: unknown) => String(error)).finally(() => vi.useRealTimers())
+
+ expect(text).not.toContain('✅')
+ })
+
it('keeps the READ_MCP gate on a project-scoped token from the /token route', async () => {
const { owner, member } = await setup({ permissions: [Permission.READ_FLOW] })
const accessToken = await mcpOAuthTokenService.issueInternalAccessToken({ userId: member.user.id, platformId: owner.platform.id, projectId: owner.project.id })
@@ -106,3 +129,5 @@ describe('In-app AI Chat on the MCP server', () => {
expect(text).toContain('✅')
})
})
+
+const LONG_TURN_MS = 45 * 60 * 1000