Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(agent-platform): remove the auth.integration MCP credential path (#65481)

Ben Whiteec9e281a8600
diff --git a/products/agent_platform/backend/logic/spec_schema.py b/products/agent_platform/backend/logic/spec_schema.py
index 3774492dcebc..2d5308bb965f 100644
--- a/products/agent_platform/backend/logic/spec_schema.py
+++ b/products/agent_platform/backend/logic/spec_schema.py
@@ -347,7 +347,6 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {
"auth": {
"type": "object",
"properties": {
- "integration": {"type": "string"},
"provider": {"type": "string"},
},
"additionalProperties": False,
@@ -418,7 +417,6 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {
"additionalProperties": False,
},
},
- "integrations": {"default": [], "type": "array", "items": {"type": "string"}},
# Identity providers users can link against. Mirror IdentityProviderConfigSchema
# in services/agent-shared/src/spec/spec.ts.
"identity_providers": {
@@ -580,7 +578,6 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {
"tools",
"mcps",
"skills",
- "integrations",
"secrets",
"limits",
"entrypoint",
diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.ts
index 2cd3352a6932..56ab8744d5dd 100644
--- a/products/agent_platform/frontend/generated/api.schemas.ts
+++ b/products/agent_platform/frontend/generated/api.schemas.ts
@@ -414,7 +414,6 @@ export type AgentRevisionApiSpecToolsItem =
}
export type AgentRevisionApiSpecMcpsItemAuth = {
- integration?: string
provider?: string
}
@@ -550,7 +549,6 @@ export type AgentRevisionApiSpec = {
tools: AgentRevisionApiSpecToolsItem[]
mcps: AgentRevisionApiSpecMcpsItem[]
skills: AgentRevisionApiSpecSkillsItem[]
- integrations: string[]
identity_providers?: AgentRevisionApiSpecIdentityProvidersItem[]
secrets: AgentRevisionApiSpecSecretsItem[]
limits: AgentRevisionApiSpecLimits
@@ -794,7 +792,6 @@ export type PatchedAgentRevisionApiSpecToolsItem =
}
export type PatchedAgentRevisionApiSpecMcpsItemAuth = {
- integration?: string
provider?: string
}
@@ -952,7 +949,6 @@ export type PatchedAgentRevisionApiSpec = {
tools: PatchedAgentRevisionApiSpecToolsItem[]
mcps: PatchedAgentRevisionApiSpecMcpsItem[]
skills: PatchedAgentRevisionApiSpecSkillsItem[]
- integrations: string[]
identity_providers?: PatchedAgentRevisionApiSpecIdentityProvidersItem[]
secrets: PatchedAgentRevisionApiSpecSecretsItem[]
limits: PatchedAgentRevisionApiSpecLimits
diff --git a/products/agent_platform/frontend/generated/api.zod.ts b/products/agent_platform/frontend/generated/api.zod.ts
index 3cefb42e473c..9d064e48f2d3 100644
--- a/products/agent_platform/frontend/generated/api.zod.ts
+++ b/products/agent_platform/frontend/generated/api.zod.ts
@@ -166,7 +166,6 @@ export const agentApplicationsRevisionsCreateBodySpecMcpsDefault = []
export const agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin = 0
export const agentApplicationsRevisionsCreateBodySpecSkillsDefault = []
-export const agentApplicationsRevisionsCreateBodySpecIntegrationsDefault = []
export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneIdDefault = `posthog`
export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneBindingDefault = `principal`
@@ -532,7 +531,6 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
url: zod.url(),
auth: zod
.object({
- integration: zod.string().optional(),
provider: zod.string().optional(),
})
.optional(),
@@ -598,7 +596,6 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
})
)
.default(agentApplicationsRevisionsCreateBodySpecSkillsDefault),
- integrations: zod.array(zod.string()).default(agentApplicationsRevisionsCreateBodySpecIntegrationsDefault),
identity_providers: zod
.array(
zod.union([
@@ -785,7 +782,6 @@ export const agentApplicationsRevisionsUpdateBodySpecMcpsDefault = []
export const agentApplicationsRevisionsUpdateBodySpecSkillsItemVersionMin = 0
export const agentApplicationsRevisionsUpdateBodySpecSkillsDefault = []
-export const agentApplicationsRevisionsUpdateBodySpecIntegrationsDefault = []
export const agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemOneIdDefault = `posthog`
export const agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemOneBindingDefault = `principal`
@@ -1151,7 +1147,6 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({
url: zod.url(),
auth: zod
.object({
- integration: zod.string().optional(),
provider: zod.string().optional(),
})
.optional(),
@@ -1217,7 +1212,6 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({
})
)
.default(agentApplicationsRevisionsUpdateBodySpecSkillsDefault),
- integrations: zod.array(zod.string()).default(agentApplicationsRevisionsUpdateBodySpecIntegrationsDefault),
identity_providers: zod
.array(
zod.union([
@@ -1427,7 +1421,6 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin = 0
export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault = []
-export const agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneIdDefault = `posthog`
export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneBindingDefault = `principal`
@@ -1809,7 +1802,6 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
url: zod.url(),
auth: zod
.object({
- integration: zod.string().optional(),
provider: zod.string().optional(),
})
.optional(),
@@ -1875,9 +1867,6 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
})
)
.default(agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault),
- integrations: zod
- .array(zod.string())
- .default(agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault),
identity_providers: zod
.array(
zod.union([
diff --git a/products/agent_platform/services/agent-runner/src/config.ts b/products/agent_platform/services/agent-runner/src/config.ts
index b25cb8f27fbe..fc6fa2beafc2 100644
--- a/products/agent_platform/services/agent-runner/src/config.ts
+++ b/products/agent_platform/services/agent-runner/src/config.ts
@@ -189,7 +189,7 @@ export const AgentRunnerConfigSchema = PlatformConfigSchema.extend({
.string()
.optional()
.describe(
- "Dev-only bearer attached to `kind: external` MCP requests when the ref has no `auth.integration` configured. Lets a local bundle (concierge) reach the dev MCP server with the operator's PAT, before per-session credential plumbing exists for external MCPs. **Refused at boot when NODE_ENV=production** — prod must route auth via integrations or `kind: agent`."
+ "Dev-only bearer attached to MCP requests when the ref has no `auth.provider` configured. Lets a local bundle (concierge) reach the dev MCP server with the operator's PAT, before per-session credential plumbing exists for external MCPs. **Refused at boot when NODE_ENV=production** — prod must route auth via `auth.provider` or a bring-your-own-token secret."
),
sandboxBackend: z
.enum(['docker', 'modal'])
diff --git a/products/agent_platform/services/agent-runner/src/index.ts b/products/agent_platform/services/agent-runner/src/index.ts
index e98af9e8a8c8..3487189cff5f 100644
--- a/products/agent_platform/services/agent-runner/src/index.ts
+++ b/products/agent_platform/services/agent-runner/src/index.ts
@@ -46,7 +46,6 @@ import {
PgIdentityCredentialStore,
PgIdentityLinkStateStore,
PgIdentityStore,
- PgIntegrationStore,
PgRevisionStore,
PgSandboxInstanceStore,
PgSessionQueue,
@@ -65,7 +64,6 @@ import { defaultApiKeyFromConfig, loadAgentRunnerConfig } from './config'
import { posthogAiGatewayModel } from './models/ai-gateway-model'
import { resolveModelCached } from './models/pi-client'
import { makeEncryptedEnvResolver } from './resolvers/encrypted-env-resolver'
-import { makeIntegrationHostValidator } from './resolvers/integration-host-registry'
import { Worker } from './workers/worker'
const log = createLogger('agent-runner')
@@ -142,19 +140,6 @@ async function main(): Promise<void> {
const encryption = new EncryptedFields(config.encryptionSaltKeys)
const resolveSecrets = makeEncryptedEnvResolver({ revisions, encryption })
- // Integration credentials live in PostHog's existing `posthog_integration`
- // table (the same one Settings → Integrations writes to and HogFunctions
- // read from). Unconditionally wired now that encryption is required.
- const integrations = new PgIntegrationStore(posthogDb, encryption)
- const resolveIntegrations = async (session: {
- team_id: number
- revision_id: string
- }): Promise<Awaited<ReturnType<typeof integrations.resolveForSpec>>> => {
- const rev = await revisions.getRevision(session.revision_id)
- const kinds = rev?.spec?.integrations ?? []
- return integrations.resolveForSpec(session.team_id, kinds)
- }
-
// Cross-process event bus. REDIS_URL is required — ingress /listen on host A
// subscribes to events the runner publishes on host B via the same Redis.
// Required in prod, enforced at config-load (config.ts).
@@ -306,7 +291,6 @@ async function main(): Promise<void> {
buildApprovalUrl: (requestId) => `${config.approvalLinkScheme}://approval/${requestId}`,
bus,
logs: logSink,
- resolveIntegrations,
resolveSecrets,
resolveModel: config.useAiGateway
? // Route every model through PostHog's ai-gateway as a drop-in proxy.
@@ -351,11 +335,6 @@ async function main(): Promise<void> {
identities,
linkRedirectBaseUrl: config.linkRedirectBaseUrl,
devMcpBearerToken: config.devMcpBearerToken,
- // Per-integration-kind host allowlist. Without this, any external MCP
- // ref with `auth.integration` fails closed at open with
- // `mcp_integration_host_validator_not_wired`. Registry seeded with
- // slack; extend in integration-host-registry.ts as kinds are added.
- integrationHostValidator: makeIntegrationHostValidator(),
http,
posthogApiBaseUrl: config.posthogApiBaseUrl,
failureNotifier,
diff --git a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts
index 6c27ff76fffa..f77ffbae1e4b 100644
--- a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.test.ts
@@ -141,7 +141,6 @@ function makeDeps(rev: AgentRevision, over: Partial<AgentToolDeps> = {}): AgentT
rev,
session: makeSession(),
sandbox: null,
- integrations: {},
secrets: {},
bundle: makeBundle(),
log: () => undefined,
diff --git a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
index c40695796589..07544321f7fd 100644
--- a/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/build-agent-tools.ts
@@ -36,7 +36,6 @@ import {
getSecretAllowedHosts,
HttpFetcher,
IdentityAuthRequiredError,
- IntegrationCredentials,
MemoryStore,
TabularStore,
Sandbox,
@@ -101,7 +100,6 @@ export interface AgentToolDeps {
rev: AgentRevision
session: AgentSession
sandbox: Sandbox | null
- integrations: Record<string, IntegrationCredentials>
/** Resolved plaintext secrets for native tools (custom tools get nonces via the sandbox). */
secrets: Record<string, string>
bundle: BundleStore
@@ -240,7 +238,7 @@ export async function buildAgentTools(rev: AgentRevision, deps: AgentToolDeps):
// code so the session-failure reason is attributable to a
// specific MCP at triage time. Matches the convention used
// by `mcp-clients.ts` for the other error paths
- // (`mcp_secret_not_resolved`, `mcp_integration_not_resolved`,
+ // (`mcp_secret_not_resolved`, `mcp_identity_unavailable`,
// `duplicate_mcp_prefix`).
throw new Error(`mcp_list_tools_failed:${client.prefix}: ${(err as Error).message}`)
}
@@ -504,7 +502,6 @@ function buildToolContext(deps: AgentToolDeps, resolvedIdentities?: ToolContext[
teamId: deps.session.team_id,
applicationId: deps.rev.application_id,
sessionId,
- integrations: deps.integrations,
secret: (name) => deps.secrets[name],
secretAllowedHosts: (name) => getSecretAllowedHosts(deps.rev.spec, name),
log: deps.log,
diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts b/products/agent_platform/services/agent-runner/src/loop/driver.test.ts
index 87e006c8fbeb..dbe244350ff6 100644
--- a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/driver.test.ts
@@ -168,7 +168,6 @@ async function run(
model: fauxModel((over.script as AssistantMessage[]) ?? [stop('ok')]),
bundle,
sandbox: null,
- integrations: {},
secrets: {},
inputs: new PgSessionQueue(pool),
bus: driverTestBus,
diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.ts
index bb097136c6fa..2be369ad42da 100644
--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts
@@ -60,7 +60,6 @@ import {
IdentityCredentialStore,
IdentityLinkStateStore,
IdentityStore,
- IntegrationCredentials,
isDeltaEventKind,
isSlackTriggerMetadata,
LogLevel,
@@ -104,7 +103,6 @@ export interface RunSessionDeps {
streamFn?: StreamFn
bundle: BundleStore
sandbox: Sandbox | null
- integrations: Record<string, IntegrationCredentials>
secrets: Record<string, string>
broker?: SecretBroker
/**
@@ -426,7 +424,6 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps
rev,
session,
sandbox: deps.sandbox,
- integrations: deps.integrations,
secrets: deps.secrets,
bundle: deps.bundle,
log,
diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.ts
index 7b71025d258c..33be4c6633f1 100644
--- a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.test.ts
@@ -110,7 +110,6 @@ describe('openMcpClients', () => {
it('returns an empty result for an empty refs list', async () => {
const { factory, pairs, targets } = await buildEchoFactory()
const { clients, close } = await openMcpClients([], {
- integrations: {},
secrets: {},
transportFactory: factory,
})
@@ -125,7 +124,6 @@ describe('openMcpClients', () => {
const refs: McpRef[] = [{ id: 'echo', url: 'https://example.com/mcp', secrets: [] }]
const { clients, close } = await openMcpClients(refs, {
- integrations: {},
secrets: {},
transportFactory: factory,
})
@@ -156,7 +154,6 @@ describe('openMcpClients', () => {
{ id: 'github', url: 'https://example.com/github', secrets: [] },
]
const { clients, close } = await openMcpClients(refs, {
- integrations: {},
secrets: {},
transportFactory: factory,
})
@@ -171,9 +168,9 @@ describe('openMcpClients', () => {
{ id: 'dup', url: 'https://example.com/a', secrets: [] },
{ id: 'dup', url: 'https://example.com/b', secrets: [] },
]
- await expect(
- openMcpClients(refs, { integrations: {}, secrets: {}, transportFactory: factory })
- ).rejects.toThrow(/duplicate_mcp_prefix: dup/)
+ await expect(openMcpClients(refs, { secrets: {}, transportFactory: factory })).rejects.toThrow(
+ /duplicate_mcp_prefix: dup/
+ )
// The duplicate-prefix path closes the clients it opened — the in-memory
// server pairs should still be drain-able by the test's own cleanup.
await closePairs(pairs)
@@ -189,7 +186,6 @@ describe('openMcpClients', () => {
},
]
const { close } = await openMcpClients(refs, {
- integrations: {},
secrets: { TENANT: 'acme' },
secretAllowedHosts: (n) => (n === 'TENANT' ? ['example.com'] : undefined),
transportFactory: factory,
@@ -218,7 +214,6 @@ describe('openMcpClients', () => {
},
]
const { close } = await openMcpClients(refs, {
- integrations: {},
secrets: { GITHUB_TOKEN: 'ghp_realtoken' },
secretAllowedHosts: (n) => (n === 'GITHUB_TOKEN' ? ['api.githubcopilot.com'] : undefined),
transportFactory: factory,
@@ -229,41 +224,10 @@ describe('openMcpClients', () => {
await closePairs(pairs)
})
- it('author headers take precedence over integration-stamped Authorization on duplicate keys', async () => {
- // Matches @posthog/http-request's "caller-set values are not silently
- // overwritten" rule. If the author explicitly sets Authorization in
- // headers AND wires auth.integration, the explicit author value wins
- // — the integration bearer falls through. Authors who want the
- // integration's token must omit Authorization from headers.
- const { factory, pairs, targets } = await buildEchoFactory()
- const refs: McpRef[] = [
- {
- id: 'fancy',
- url: 'https://example.com/mcp',
- secrets: ['CUSTOM_TOKEN'],
- auth: { integration: 'slack:T01' },
- headers: { Authorization: 'Bearer ${CUSTOM_TOKEN}' },
- },
- ]
- const { close } = await openMcpClients(refs, {
- integrations: {
- 'slack:T01': { kind: 'slack', access_token: 'xoxb-from-integration' },
- },
- secrets: { CUSTOM_TOKEN: 'custom-from-secret' },
- secretAllowedHosts: (n) => (n === 'CUSTOM_TOKEN' ? ['example.com'] : undefined),
- transportFactory: factory,
- integrationHostValidator: () => true,
- })
- expect(targets[0].headers.Authorization).toBe('Bearer custom-from-secret')
- await close()
- await closePairs(pairs)
- })
-
it('auth.provider stamps the asker bearer when the identity resolves ok', async () => {
const { factory, pairs, targets } = await buildEchoFactory()
const refs: McpRef[] = [{ id: 'gh', url: 'https://example.com/mcp', secrets: [], auth: { provider: 'github' } }]
const { close } = await openMcpClients(refs, {
- integrations: {},
secrets: {},
transportFactory: factory,
identity: {
@@ -283,7 +247,6 @@ describe('openMcpClients', () => {
const { factory, pairs } = await buildEchoFactory()
const refs: McpRef[] = [{ id: 'gh', url: 'https://example.com/mcp', secrets: [], auth: { provider: 'github' } }]
const { clients, failures, close } = await openMcpClients(refs, {
- integrations: {},
secrets: {},
transportFactory: factory,
identity: {
@@ -318,7 +281,6 @@ describe('openMcpClients', () => {
]
const relink = vi.fn(async () => 'https://app.posthog.test/oauth/authorize/?reconnect=1')
const { clients, failures } = await openMcpClients(refs, {
- integrations: {},
secrets: {},
transportFactory: failingFactory,
identity: {
@@ -343,7 +305,6 @@ describe('openMcpClients', () => {
{ id: 'gh', url: 'https://evil.example/mcp', secrets: [], auth: { provider: 'github' } },
]
const { clients, failures, close } = await openMcpClients(refs, {
- integrations: {},
secrets: {},
transportFactory: factory,
identity: {
@@ -366,7 +327,6 @@ describe('openMcpClients', () => {
{ id: 'posthog', url: 'http://localhost:8787/mcp', secrets: [], auth: { provider: 'posthog' } },
]
const { close } = await openMcpClients(refs, {
- integrations: {},
secrets: {},
transportFactory: factory,
identity: {
@@ -399,7 +359,6 @@ describe('openMcpClients', () => {
},
]
const { clients, close, failures } = await openMcpClients(refs, {
- integrations: {},
secrets: {},
transportFactory: factory,
})
@@ -422,7 +381,6 @@ describe('openMcpClients', () => {
},
]
const { clients, close, failures } = await openMcpClients(refs, {
- integrations: {},
secrets: {},
transportFactory: factory,
})
@@ -450,7 +408,6 @@ describe('openMcpClients', () => {
},
]
const { clients, close, failures } = await openMcpClients(refs, {
- integrations: {},
secrets: { SLACK_BOT_TOKEN: 'xoxb-secret' },
secretAllowedHosts: (n) => (n === 'SLACK_BOT_TOKEN' ? ['slack.com'] : undefined),
transportFactory: factory,
@@ -466,8 +423,8 @@ describe('openMcpClients', () => {
it('SECURITY: refuses to substitute a bare-string (unbound) header secret (fail closed)', async () => {
// A secret declared in spec.secrets[] as a bare string carries no
- // network-egress authority — same fail-closed shape as the unwired
- // integration-host-validator branch.
+ // network-egress authority — it fails closed rather than being
+ // stamped onto a request to an unverified host.
const { factory, pairs } = await buildEchoFactory()
const refs: McpRef[] = [
{
@@ -478,7 +435,6 @@ describe('openMcpClients', () => {
},
]
const { clients, close, failures } = await openMcpClients(refs, {
- integrations: {},
secrets: { GITHUB_TOKEN: 'ghp_realtoken' },
// null = declared as a bare string in spec.secrets[].
secretAllowedHosts: (n) => (n === 'GITHUB_TOKEN' ? null : undefined),
@@ -505,7 +461,6 @@ describe('openMcpClients', () => {
},
]
const { clients, close, failures } = await openMcpClients(refs, {
- integrations: {},
secrets: { GITHUB_TOKEN: 'ghp_realtoken' },
transportFactory: factory,
})
@@ -528,7 +483,6 @@ describe('openMcpClients', () => {
},
]
const { clients, close, failures } = await openMcpClients(refs, {
- integrations: {},
secrets: { TENANT: 'super-secret-tenant' },
secretAllowedHosts: (n) => (n === 'TENANT' ? ['example.com'] : undefined),
transportFactory: factory,
@@ -553,7 +507,6 @@ describe('openMcpClients', () => {
},
]
const { close } = await openMcpClients(refs, {
- integrations: {},
secrets: { SVC_TOKEN: 'tok_ok' },
secretAllowedHosts: (n) => (n === 'SVC_TOKEN' ? ['*.example.com'] : undefined),
transportFactory: factory,
@@ -563,174 +516,10 @@ describe('openMcpClients', () => {
await closePairs(pairs)
})
- it('stamps Authorization: Bearer <token> when auth.integration is set and the validator allows the host', async () => {
- const { factory, pairs, targets } = await buildEchoFactory()
- const refs: McpRef[] = [
- {
- id: 'linear',
- url: 'https://example.com/linear',
- secrets: [],
- auth: { integration: 'linear:T01' },
- },
- ]
- const { close } = await openMcpClients(refs, {
- integrations: {
- 'linear:T01': { kind: 'linear', access_token: 'tok_abc' },
- },
- secrets: {},
- transportFactory: factory,
- integrationHostValidator: () => true,
- })
- expect(targets[0].headers).toEqual({ Authorization: 'Bearer tok_abc' })
- await close()
- await closePairs(pairs)
- })
-
- it('SECURITY: refuses to attach integration bearer when no host validator is wired (reported as unavailable)', async () => {
- // Fail-closed: a deploy that doesn't wire `integrationHostValidator`
- // must NOT silently regress to "attach bearer to whatever URL the
- // spec author chose." Without this, a malicious author could point
- // at their own URL and harvest the team's OAuth token. The MCP is
- // captured as unavailable (degraded session) rather than thrown so
- // a deploy regression on ONE integration doesn't blow up every
- // session that references it — the bearer is still NEVER attached.
- const { factory, pairs } = await buildEchoFactory()
- const refs: McpRef[] = [
- {
- id: 'linear',
- url: 'https://example.com/linear',
- secrets: [],
- auth: { integration: 'linear:T01' },
- },
- ]
- const { clients, close, failures } = await openMcpClients(refs, {
- integrations: { 'linear:T01': { kind: 'linear', access_token: 'tok_abc' } },
- secrets: {},
- transportFactory: factory,
- })
- expect(clients).toEqual([])
- expect(failures[0].category).toBe('auth')
- expect(failures[0].devReason).toMatch(/mcp_integration_host_validator_not_wired: linear:T01/)
- await close()
- await closePairs(pairs)
- })
-
- it('SECURITY: refuses to attach integration bearer when validator rejects the host (reported as unavailable)', async () => {
- const { factory, pairs } = await buildEchoFactory()
- const refs: McpRef[] = [
- {
- id: 'linear',
- url: 'https://evil.example.com/linear',
- secrets: [],
- auth: { integration: 'linear:T01' },
- },
- ]
- const { clients, close, failures } = await openMcpClients(refs, {
- integrations: { 'linear:T01': { kind: 'linear', access_token: 'tok_abc' } },
- secrets: {},
- transportFactory: factory,
- integrationHostValidator: (ref, url) =>
- // Mimic a prod validator that only allows the canonical
- // host for a known integration kind.
- ref === 'linear:T01' && url.host === 'mcp.linear.app',
- })
- expect(clients).toEqual([])
- expect(failures[0].category).toBe('auth')
- expect(failures[0].devReason).toMatch(/mcp_integration_host_not_allowed: linear:T01 → evil\.example\.com/)
- await close()
- await closePairs(pairs)
- })
-
- it('SECURITY: refuses to attach integration bearer over plaintext http (reported as unavailable)', async () => {
- // Smokescreen owns SSRF but filters by destination, not scheme — it
- // won't stop the team's OAuth bearer being sent in cleartext to an
- // allowlisted public host. The host validator only checks `url.host`,
- // so the https-only guard is the runner's job on the credential path.
- const { factory, pairs } = await buildEchoFactory()
- const refs: McpRef[] = [
- {
- id: 'linear',
- url: 'http://mcp.linear.app/linear',
- secrets: [],
- auth: { integration: 'linear:T01' },
- },
- ]
- const { clients, close, failures } = await openMcpClients(refs, {
- integrations: { 'linear:T01': { kind: 'linear', access_token: 'tok_abc' } },
- secrets: {},
- transportFactory: factory,
- // Host is allowed — only the scheme should reject it.
- integrationHostValidator: () => true,
- })
- expect(clients).toEqual([])
- expect(failures[0].category).toBe('auth')
- expect(failures[0].devReason).toMatch(/mcp_integration_unsafe_scheme: linear:T01 → http:/)
- await close()
- await closePairs(pairs)
- })
-
- it('reports mcp_integration_not_resolved as an unavailable MCP (auth category)', async () => {
- const { factory, pairs } = await buildEchoFactory()
- const refs: McpRef[] = [
- {
- id: 'linear',
- url: 'https://example.com/linear',
- secrets: [],
- auth: { integration: 'linear:T01' },
- },
- ]
- const { clients, close, failures } = await openMcpClients(refs, {
- integrations: {},
- secrets: {},
- transportFactory: factory,
- })
- expect(clients).toEqual([])
- expect(failures[0].category).toBe('auth')
- expect(failures[0].devReason).toMatch(/mcp_integration_not_resolved: linear:T01/)
- await close()
- await closePairs(pairs)
- })
-
- it('on partial open: keeps the successful clients alive and records the bad ones as failures', async () => {
- const { factory, pairs, targets } = await buildEchoFactory()
- // First ref opens cleanly; second ref fails during target resolution
- // (missing integration). Under the degraded-MCP contract the session
- // continues with `ok`, and `broken` is reported via `failures`.
- const refs: McpRef[] = [
- { id: 'ok', url: 'https://example.com/a', secrets: [] },
- {
- id: 'broken',
- url: 'https://example.com/b',
- secrets: [],
- auth: { integration: 'missing' },
- },
- ]
- const { clients, close, failures } = await openMcpClients(refs, {
- integrations: {},
- secrets: {},
- transportFactory: factory,
- })
- expect(clients.map((c) => c.prefix)).toEqual(['ok'])
- expect(failures).toHaveLength(1)
- expect(failures[0].ref.id).toBe('broken')
- expect(failures[0].category).toBe('auth')
- expect(failures[0].devReason).toMatch(/mcp_integration_not_resolved/)
- expect(targets.length).toBeGreaterThanOrEqual(1)
- // The good client is still usable.
- const okPair = pairs[0]
- expect(okPair).not.toBeUndefined()
- expect(okPair.serverClosed.value).toBe(false)
- await close()
- // close() shut down the surviving client.
- expect(okPair.serverClosed.value).toBe(true)
- await closePairs(pairs)
- })
-
it('surfaces remote tool errors as isError on the McpCallResult', async () => {
const { factory, pairs } = await buildEchoFactory()
const refs: McpRef[] = [{ id: 'echo', url: 'https://example.com/mcp', secrets: [] }]
const { clients, close } = await openMcpClients(refs, {
- integrations: {},
secrets: {},
transportFactory: factory,
})
@@ -766,7 +555,6 @@ describe('openMcpClients', () => {
}
const refs: McpRef[] = [{ id: 'echo', url: 'https://example.com/mcp', secrets: [] }]
const { clients, close } = await openMcpClients(refs, {
- integrations: {},
secrets: {},
transportFactory: factory,
log: (level, msg, meta) => {
@@ -787,7 +575,6 @@ describe('openMcpClients', () => {
it('attaches Authorization: Bearer when ref has no auth and a dev bearer is configured', async () => {
const { factory, pairs, targets } = await buildEchoFactory()
const { close } = await openMcpClients([{ id: 'x', url: 'https://mcp.example.com/sse', secrets: [] }], {
- integrations: {},
secrets: {},
transportFactory: factory,
devMcpBearerToken: 'phx_dev_token',
@@ -797,30 +584,9 @@ describe('openMcpClients', () => {
await closePairs(pairs)
})
- it('does NOT attach the dev bearer when ref.auth.integration is set (integration wins)', async () => {
- const { factory, pairs, targets } = await buildEchoFactory()
- const ref: McpRef = {
- id: 'x',
- url: 'https://mcp.example.com/sse',
- secrets: [],
- auth: { integration: 'linear:acme' },
- }
- const { close } = await openMcpClients([ref], {
- integrations: { 'linear:acme': { access_token: 'integration_token', kind: 'linear' } },
- secrets: {},
- transportFactory: factory,
- devMcpBearerToken: 'phx_dev_token',
- integrationHostValidator: () => true,
- })
- expect(targets[0].headers.Authorization).toBe('Bearer integration_token')
- await close()
- await closePairs(pairs)
- })
-
- it('omits Authorization entirely when neither auth.integration nor a dev bearer is set', async () => {
+ it('omits Authorization entirely when no auth and no dev bearer is set', async () => {
const { factory, pairs, targets } = await buildEchoFactory()
const { close } = await openMcpClients([{ id: 'x', url: 'https://mcp.example.com/sse', secrets: [] }], {
- integrations: {},
secrets: {},
transportFactory: factory,
})
diff --git a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.ts b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.ts
index e59fd01b228d..5b0ff9d1625b 100644
--- a/products/agent_platform/services/agent-runner/src/loop/mcp-clients.ts
+++ b/products/agent_platform/services/agent-runner/src/loop/mcp-clients.ts
@@ -9,10 +9,10 @@
* - `close()` — best-effort transport shutdown.
*
* Auth resolution:
- * - `auth.integration` → `integrations[ref].access_token` →
- * `Authorization: Bearer <token>`. Host-bound by the worker's
- * `integrationHostValidator` so a spec author can't redirect a team's
- * OAuth token to an arbitrary URL.
+ * - `auth.provider` → resolve the asker's linked identity via `ctx.identity`
+ * → `Authorization: Bearer <token>`. Host-bound by the provider's own
+ * `allowedHosts()` so a spec author can't redirect a user's OAuth token to
+ * an arbitrary URL; an unlinked asker surfaces a relayable authorize link.
* - `secrets[]` → resolve each name via `secrets[NAME]`; substitute
* `${NAME}` placeholders in the URL + author-supplied headers before
* opening the transport. Each substitution is gated on the secret's
@@ -45,14 +45,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'
-import {
- HttpFetcher,
- type IdentityResolution,
- IntegrationCredentials,
- isDev,
- McpRef,
- secretHostMatches,
-} from '@posthog/agent-shared'
+import { HttpFetcher, type IdentityResolution, isDev, McpRef, secretHostMatches } from '@posthog/agent-shared'
/** Remote tool descriptor as returned by `client.listTools()`. */
export interface RemoteMcpTool {
@@ -89,7 +82,7 @@ export interface OpenedMcp {
* provider-side stack hints). The agent owner gets the full reason via
* log_entries.
* - `auth` — credentials / token / secret resolution problem
- * (`mcp_secret_not_resolved`, `mcp_integration_*`,
+ * (`mcp_secret_not_resolved`, `mcp_identity_*`,
* 401/403 from the remote)
* - `network` — couldn't reach the server (DNS, refused, timeout, 5xx)
* - `not_found` — server responded but said the endpoint is gone (404, 410)
@@ -135,7 +128,6 @@ export function categorizeMcpOpenError(err: Error): McpFailureCategory {
const msg = err.message.toLowerCase()
if (
msg.includes('mcp_secret_') ||
- msg.includes('mcp_integration_') ||
msg.includes('mcp_identity_') ||
msg.includes('no token') ||
msg.includes('unauthor') ||
@@ -178,20 +170,7 @@ export function categorizeMcpOpenError(err: Error): McpFailureCategory {
*/
export type McpTransportFactory = (target: { url: string; headers: Record<string, string> }) => Transport
-/**
- * Per-call validator the runner consults before stamping a connected
- * integration's bearer token on an outbound MCP request. Returns `true` to
- * allow attachment, `false` to reject. The worker is expected to wire a
- * validator that maps the integration kind (e.g. `linear`, `github`) to
- * the host pattern that integration is authorised for; without a wired
- * validator, every `auth.integration`-bearing ref is **refused at open
- * time** so a malicious spec author can't redirect a team's OAuth token
- * to an arbitrary URL.
- */
-export type IntegrationHostValidator = (integrationRef: string, url: URL) => boolean
-
export interface OpenMcpClientsDeps {
- integrations: Record<string, IntegrationCredentials>
/** Resolved plaintext secrets keyed by name (same shape `runSession`
* already threads through). Only the names listed on a given ref's
* `secrets[]` are substituted into that ref's URL. */
@@ -214,19 +193,10 @@ export interface OpenMcpClientsDeps {
/** Identity sent during the MCP `initialize` handshake. Defaults to the
* runner's own name + a static version stamp. */
clientInfo?: { name: string; version: string }
- /**
- * Validator that decides whether a connected integration's bearer token
- * may be attached to a given MCP URL. Fail-closed: when unset, any
- * `auth.integration`-bearing external ref is refused at open time
- * (`mcp_integration_host_validator_not_wired`). See the type definition
- * for the threat model.
- */
- integrationHostValidator?: IntegrationHostValidator
/**
* Per-asker identity resolver (from `buildAskerIdentity`). Resolves a
- * `ref.auth.provider` to the asker's bearer, same posture as
- * `auth.integration` (https + the resolver's own host allowlist). Absent →
- * any `auth.provider` ref is refused at open time.
+ * `ref.auth.provider` to the asker's bearer (https + the resolver's own
+ * host allowlist). Absent → any `auth.provider` ref is refused at open time.
*/
identity?: {
resolve(provider: string, scopes?: string[]): Promise<IdentityResolution>
@@ -236,11 +206,10 @@ export interface OpenMcpClientsDeps {
relink?(provider: string): Promise<string | null>
}
/**
- * Dev-only bearer attached to `kind: external` MCP requests when the
- * ref has no `auth.integration` of its own (`ref.auth` wins if set).
- * Bridges the local-dev auth gap until external-MCP credentials are
- * sourced from the per-session credential broker. Production refuses
- * to set this at boot.
+ * Dev-only bearer attached to MCP requests when the ref has no
+ * `auth.provider` of its own (`ref.auth` wins if set). Bridges the
+ * local-dev auth gap until external-MCP credentials are sourced from
+ * the per-session credential broker. Production refuses to set this at boot.
*/
devMcpBearerToken?: string
/**
@@ -385,7 +354,8 @@ async function resolveTarget(
// Author chose the URL; smokescreen denies RFC1918 / loopback /
// link-local / cloud-IMDS + closes the DNS-rebinding gap via per-IP
// resolution at connect time. The runner only handles the logical-binding
- // check (integration → host allowlist), which smokescreen can't do.
+ // check (identity provider → its own host allowlist), which smokescreen
+ // can't do.
//
// Fail-closed when the host lookup isn't wired: treat every secret as
// unbound so substitution refuses rather than sending it to any host.
@@ -397,37 +367,7 @@ async function resolveTarget(
// `@posthog/http-request`'s URL-first host binding.
const { url, host } = substituteUrlAndExtractHost(ref.url, ref.secrets, allowedHostsFor, deps.secrets)
const headers: Record<string, string> = {}
- if (ref.auth?.integration) {
- const cred = deps.integrations[ref.auth.integration]
- if (!cred) {
- throw new Error(`mcp_integration_not_resolved: ${ref.auth.integration}`)
- }
- // Fail-closed integration host binding: an author can't redirect a
- // team's OAuth token to an arbitrary URL because the worker's
- // validator gates which host each integration kind is allowed to
- // talk to. The unwired-validator branch refuses unconditionally so
- // a config-drift / deploy issue can't silently regress to "attach
- // bearer to anything." See `IntegrationHostValidator` doc + the
- // PR-6 security thread.
- if (!deps.integrationHostValidator) {
- throw new Error(`mcp_integration_host_validator_not_wired: ${ref.auth.integration}`)
- }
- const parsed = new URL(url)
- // Smokescreen owns SSRF, but it can't guarantee the OAuth bearer isn't
- // sent in cleartext to an allowlisted public host — it filters by
- // destination, not scheme. The host validator below only checks
- // `url.host`, so without this an author could set `http://api.slack.com`
- // and have the team's token stamped onto a plaintext request. Enforce
- // https on the credential path only; non-auth external URLs stay
- // smokescreen's concern.
- if (parsed.protocol !== 'https:') {
- throw new Error(`mcp_integration_unsafe_scheme: ${ref.auth.integration} → ${parsed.protocol}`)
- }
- if (!deps.integrationHostValidator(ref.auth.integration, parsed)) {
- throw new Error(`mcp_integration_host_not_allowed: ${ref.auth.integration} → ${parsed.host}`)
- }
- headers['Authorization'] = `Bearer ${cred.access_token}`
- } else if (ref.auth?.provider) {
+ if (ref.auth?.provider) {
if (!deps.identity) {
throw new Error(`mcp_identity_not_wired: ${ref.auth.provider}`)
}
@@ -463,14 +403,14 @@ async function resolveTarget(
}
headers['Authorization'] = `Bearer ${token}`
} else if (deps.devMcpBearerToken) {
- // Dev-only fallback. The bundle declared no integration auth, but
+ // Dev-only fallback. The bundle declared no provider auth, but
// the operator wired a global dev bearer (their PAT, typically) so
// the local MCP server accepts the call. `ref.auth` always wins
// when set; this branch only fires when the spec is auth-less.
headers['Authorization'] = `Bearer ${deps.devMcpBearerToken}`
}
// Author-supplied headers — the BYO-bearer-token path. Walked after the
- // integration / dev-bearer blocks so explicit author entries take
+ // provider / dev-bearer blocks so explicit author entries take
// precedence on duplicate keys (matches `http-request`'s "caller-set
// values are not silently overwritten" rule). Each `${NAME}` is gated on
// the secret's `allowed_hosts` against the final URL host — a header
diff --git a/products/agent_platform/services/agent-runner/src/resolvers/integration-host-registry.test.ts b/products/agent_platform/services/agent-runner/src/resolvers/integration-host-registry.test.ts
deleted file mode 100644
index 212f38659f67..000000000000
--- a/products/agent_platform/services/agent-runner/src/resolvers/integration-host-registry.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { INTEGRATION_HOST_REGISTRY, makeIntegrationHostValidator } from './integration-host-registry'
-
-describe('makeIntegrationHostValidator', () => {
- const validate = makeIntegrationHostValidator(INTEGRATION_HOST_REGISTRY)
-
- it.each([
- { label: 'slack REST root', host: 'slack.com' },
- { label: 'slack api subdomain', host: 'api.slack.com' },
- { label: 'slack mcp subdomain', host: 'mcp.slack.com' },
- ])('allows the slack integration against $label', ({ host }) => {
- expect(validate('slack:T01XXX', new URL(`https://${host}/api/chat.postMessage`))).toBe(true)
- })
-
- it.each([
- { label: 'arbitrary public host', host: 'evil.com' },
- { label: 'host that *contains* a known TLD', host: 'slack.com.evil.com' },
- { label: 'lookalike host', host: 'sl4ck.com' },
- { label: 'wrong subdomain', host: 'wrong.slack.com' },
- ])('rejects the slack integration against $label', ({ host }) => {
- expect(validate('slack:T01XXX', new URL(`https://${host}/anything`))).toBe(false)
- })
-
- it('rejects unknown integration kinds (fail-closed)', () => {
- expect(validate('linear:abc', new URL('https://mcp.linear.app/'))).toBe(false)
- })
-
- it.each([
- { label: 'no colon', ref: 'slack' },
- { label: 'empty kind', ref: ':T01XXX' },
- { label: 'empty string', ref: '' },
- ])('rejects malformed integration refs ($label)', ({ ref }) => {
- expect(validate(ref, new URL('https://slack.com/'))).toBe(false)
- })
-})
diff --git a/products/agent_platform/services/agent-runner/src/resolvers/integration-host-registry.ts b/products/agent_platform/services/agent-runner/src/resolvers/integration-host-registry.ts
deleted file mode 100644
index 2f918f7caabb..000000000000
--- a/products/agent_platform/services/agent-runner/src/resolvers/integration-host-registry.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * Per-integration-kind host allowlist for outbound MCP requests.
- *
- * Threat model: a bundle author can write any URL into `mcps[].url` plus an
- * `auth.integration` reference. Without a host check the runner would attach
- * the team's connected OAuth token (Slack, Linear, etc.) to whatever URL the
- * author wanted — exfiltration. SSRF protection itself lives at the infra
- * layer (smokescreen denies RFC1918 / loopback / link-local + closes the
- * DNS-rebinding gap), but smokescreen has no concept of *which* integration's
- * bearer is being attached — it sees "this pod wants to call that host" and
- * has no way to know "the linear bearer must only go to mcp.linear.app". This
- * registry closes that logical-binding gap by binding each integration kind
- * to a fixed list of host patterns.
- *
- * The registry is **append-only**: adding a kind is one entry; removing or
- * narrowing a kind's hosts breaks existing bundles that already authored
- * against the wider set.
- *
- * `integrationRef` shape — `<kind>:<integration_id>` (e.g. `slack:T01XXX`).
- * Mirrors `IntegrationStore.resolveForSpec` which keys the credential map
- * the same way. An unknown kind always returns false (fail-closed).
- */
-
-import { IntegrationHostValidator } from '../loop/mcp-clients'
-
-export const INTEGRATION_HOST_REGISTRY: Record<string, ReadonlyArray<RegExp>> = {
- // Slack: REST API (`slack.com/api/...`) and the future hosted MCP server.
- // Both `chat.postMessage` and friends route through `slack.com`; subdomain
- // variants are kept explicit so a typo in `slackcompany.com` can't
- // accidentally match.
- slack: [/^slack\.com$/, /^api\.slack\.com$/, /^mcp\.slack\.com$/],
-}
-
-/**
- * Build a validator from a host registry. Parses `<kind>:<id>` and matches
- * `url.host` against the registry's patterns for that kind. Unknown kinds
- * and unmatched hosts return false; the caller refuses to attach the bearer.
- */
-export function makeIntegrationHostValidator(
- registry: Record<string, ReadonlyArray<RegExp>> = INTEGRATION_HOST_REGISTRY
-): IntegrationHostValidator {
- return (integrationRef: string, url: URL): boolean => {
- const colon = integrationRef.indexOf(':')
- if (colon <= 0) {
- return false
- }
- const kind = integrationRef.slice(0, colon)
- const patterns = registry[kind]
- if (!patterns) {
- return false
- }
- return patterns.some((p) => p.test(url.host))
- }
-}
diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.test.ts b/products/agent_platform/services/agent-runner/src/workers/worker.test.ts
index b44c1081bc11..d49452e6db5c 100644
--- a/products/agent_platform/services/agent-runner/src/workers/worker.test.ts
+++ b/products/agent_platform/services/agent-runner/src/workers/worker.test.ts
@@ -151,7 +151,6 @@ describe('Worker', () => {
bus: workerTestBus,
logs: workerTestLogs,
approvals: new PgApprovalStore(pool),
- resolveIntegrations: async () => ({}),
resolveSecrets: async () => ({}),
resolveModel: () => fauxModel([endTurn('hi back')]),
})
@@ -221,7 +220,6 @@ describe('Worker', () => {
bus: workerTestBus,
logs: workerTestLogs,
approvals: new PgApprovalStore(pool),
- resolveIntegrations: async () => ({}),
resolveSecrets: async () => ({ ACME_KEY: 'topsecret' }),
resolveModel: () => fauxModel([toolUseTurn([toolCall('noop', {})]), endTurn('done')]),
})
@@ -315,7 +313,6 @@ describe('Worker', () => {
bus: workerTestBus,
logs: workerTestLogs,
approvals: new PgApprovalStore(pool),
- resolveIntegrations: async () => ({}),
resolveSecrets: async () => ({}),
resolveModel: () =>
fauxModel([toolUseTurn([toolCall('echo__echo', { msg: 'hi there' })]), endTurn('done')]),
@@ -384,7 +381,6 @@ describe('Worker', () => {
bus: workerTestBus,
logs: workerTestLogs,
approvals: new PgApprovalStore(pool),
- resolveIntegrations: async () => ({}),
resolveSecrets: async () => ({}),
resolveModel: () =>
fauxModel([
@@ -456,7 +452,6 @@ describe('Worker', () => {
bus: workerTestBus,
logs: workerTestLogs,
approvals: new PgApprovalStore(pool),
- resolveIntegrations: async () => ({}),
resolveSecrets: async () => ({}),
resolveModel: () => fauxModel([endTurn('would never run')]),
})
@@ -467,8 +462,8 @@ describe('Worker', () => {
expect(after!.state).toBe('failed')
})
- // The pre-flight inside `runOne` (revision load, secrets, integrations,
- // sandbox acquire, custom-tool bundle reads) sits under one try/catch.
+ // The pre-flight inside `runOne` (revision load, secrets, sandbox
+ // acquire, custom-tool bundle reads) sits under one try/catch.
// Each failure mode below would crash the worker loop pre-fix; the
// boundary now fails just the one session.
type FailureCase = {
@@ -476,7 +471,6 @@ describe('Worker', () => {
withCustomTool: boolean
overrides: (failingPool: InProcessSandboxPool) => Partial<{
resolveSecrets: () => Promise<Record<string, string>>
- resolveIntegrations: () => Promise<Record<string, never>>
sandboxes: InProcessSandboxPool
resolveModel: (specModel: string) => never
}>
@@ -491,15 +485,6 @@ describe('Worker', () => {
},
}),
},
- {
- name: 'resolveIntegrations throws',
- withCustomTool: false,
- overrides: () => ({
- resolveIntegrations: async () => {
- throw new Error('integrations service unavailable')
- },
- }),
- },
{
name: 'sandboxes.acquireForSession throws',
withCustomTool: true,
@@ -587,7 +572,6 @@ describe('Worker', () => {
bus: workerTestBus,
logs: workerTestLogs,
approvals: new PgApprovalStore(pool),
- resolveIntegrations: async () => ({}),
resolveSecrets: async () => ({}),
resolveModel: () => fauxModel([endTurn('would never run')]),
...overrides(failingPool),
@@ -696,7 +680,6 @@ describe('Worker', () => {
bus: stubBus as unknown as RedisSessionEventBus,
logs: stubLogs as unknown as KafkaLogSink,
approvals: new PgApprovalStore(pool),
- resolveIntegrations: async () => ({}),
// Pick a deterministic pre-runSession failure — `resolveSecrets`
// throws before the driver runs.
resolveSecrets: async () => {
@@ -743,7 +726,6 @@ describe('Worker', () => {
bus: workerTestBus,
logs: workerTestLogs,
approvals: new PgApprovalStore(pool),
- resolveIntegrations: async () => ({}),
resolveSecrets: async () => ({}),
resolveModel: () => fauxModel([]),
})
@@ -779,7 +761,6 @@ describe('Worker', () => {
bus: workerTestBus,
logs: workerTestLogs,
approvals: new PgApprovalStore(pool),
- resolveIntegrations: async () => ({}),
resolveSecrets: async () => ({}),
resolveModel: () => fauxModel([]),
})
diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.ts b/products/agent_platform/services/agent-runner/src/workers/worker.ts
index 68f5f9734fd4..4faa1af5919a 100644
--- a/products/agent_platform/services/agent-runner/src/workers/worker.ts
+++ b/products/agent_platform/services/agent-runner/src/workers/worker.ts
@@ -51,7 +51,7 @@ import {
} from '@posthog/agent-shared'
import { runSession } from '../loop/driver'
-import { IntegrationHostValidator, McpTransportFactory, openMcpClients } from '../loop/mcp-clients'
+import { McpTransportFactory, openMcpClients } from '../loop/mcp-clients'
import * as metrics from '../metrics'
import { resolveModelCached } from '../models/pi-client'
@@ -65,9 +65,6 @@ export interface WorkerDeps {
broker: SecretBroker
/** Resolved per-application secrets — wire from the team's encrypted env. */
resolveSecrets: (session: AgentSession) => Promise<Record<string, string>>
- resolveIntegrations: (
- session: AgentSession
- ) => Promise<Record<string, { kind: string; access_token: string; refresh_token?: string }>>
/**
* Resolve a session's spec.model string to a concrete pi-ai Model. Defaults
* to `resolveModelCached(spec.model)` which works for built-in providers.
@@ -187,16 +184,6 @@ export interface WorkerDeps {
* instrumentation / retry middleware.
*/
mcpTransportFactory?: McpTransportFactory
- /**
- * Per-call validator that gates attaching a connected integration's
- * bearer token to an outbound MCP request. **Required to use
- * `auth.integration` on any `external` MCP ref** — without it,
- * `openMcpClients` fails closed (a spec author can't redirect a
- * team's OAuth token to an arbitrary URL). Production wires this
- * against a per-integration-kind host registry (`linear:*` →
- * `mcp.linear.app`, etc.); tests can supply `() => true` to opt-in.
- */
- integrationHostValidator?: IntegrationHostValidator
/**
* Dev-only bearer forwarded to `openMcpClients`. See `OpenMcpClientsDeps`.
* Sourced from `AGENT_DEV_MCP_BEARER_TOKEN`; the runner's `index.ts`
@@ -403,7 +390,6 @@ export class Worker {
// Friendly name for the session's `$ai_trace` (LLM Analytics). Best-
// effort — a missing app just falls back to the id in the driver.
const application = await this.deps.revisions.getApplication(session.application_id).catch(() => null)
- const integrations = await this.deps.resolveIntegrations(session)
const secrets = await this.deps.resolveSecrets(session)
const customTools = rev.spec.tools.filter((t) => t.kind === 'custom')
if (customTools.length > 0) {
@@ -475,7 +461,7 @@ export class Worker {
let mcpFailures: Awaited<ReturnType<typeof openMcpClients>>['failures'] = []
if (rev.spec.mcps.length > 0) {
// Build the per-asker resolver only when an MCP needs it (auth.provider),
- // so the common auth.integration / secret path pays nothing.
+ // so the common secret / BYO-token path pays nothing.
const mcpNeedsIdentity = rev.spec.mcps.some((m) => m.auth?.provider)
const mcpIdentity =
mcpNeedsIdentity && this.deps.identityCredentials && this.deps.identityLinks
@@ -492,11 +478,9 @@ export class Worker {
})
: undefined
const opened = await openMcpClients(rev.spec.mcps, {
- integrations,
secrets,
secretAllowedHosts: (name) => getSecretAllowedHosts(rev.spec, name),
transportFactory: this.deps.mcpTransportFactory,
- integrationHostValidator: this.deps.integrationHostValidator,
identity: mcpIdentity,
devMcpBearerToken: this.deps.devMcpBearerToken,
log: (level, msg, meta) => sLog[level](meta ?? {}, msg),
@@ -544,7 +528,6 @@ export class Worker {
apiKey,
bundle: this.deps.bundle,
sandbox,
- integrations,
secrets,
broker: this.deps.broker,
bus: this.deps.bus,
diff --git a/products/agent_platform/services/agent-shared/src/config/platform.ts b/products/agent_platform/services/agent-shared/src/config/platform.ts
index 7b617f809f07..7619853c2fa9 100644
--- a/products/agent_platform/services/agent-shared/src/config/platform.ts
+++ b/products/agent_platform/services/agent-shared/src/config/platform.ts
@@ -118,7 +118,7 @@ export const PlatformConfigSchema = z.object({
.url()
.default('postgres://posthog:posthog@localhost:5432/posthog')
.describe(
- 'Main PostHog DB — read for cross-product data only (posthog_integration, users, org membership). No agent tables.'
+ 'Main PostHog DB — read for cross-product data only (users, teams, org membership). No agent tables.'
),
agentDbUrl: z
.string()
diff --git a/products/agent_platform/services/agent-shared/src/index.ts b/products/agent_platform/services/agent-shared/src/index.ts
index 4c257a8ef66e..d35c03c498ed 100644
--- a/products/agent_platform/services/agent-shared/src/index.ts
+++ b/products/agent_platform/services/agent-shared/src/index.ts
@@ -27,7 +27,6 @@ export * from './persistence/queue'
export * from './persistence/revision-store'
export * from './persistence/identity-store'
export * from './persistence/identity-admin-store'
-export * from './persistence/integration-store'
export * from './persistence/approval-store'
export * from './persistence/approval-decision'
export * from './persistence/create-pool'
diff --git a/products/agent_platform/services/agent-shared/src/persistence/integration-store.ts b/products/agent_platform/services/agent-shared/src/persistence/integration-store.ts
deleted file mode 100644
index 1ca26d1355e4..000000000000
--- a/products/agent_platform/services/agent-shared/src/persistence/integration-store.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-/**
- * Read-only access to PostHog's `posthog_integration` table — the same table
- * Settings → Integrations writes to and HogFunctions read from. Lets the
- * agent runner resolve `spec.integrations` to live OAuth credentials at
- * session start, and the agent ingress fetch the team's Slack bot token
- * when it needs to post (elevation message, owner-DM notification, etc.).
- *
- * The store does NOT cache. Reads are rare (once per session start in the
- * runner; once per rejected message in the ingress) and the underlying
- * Integration row may be rotated by the user at any time. If profiling
- * surfaces this as a hot path, slot in an LRU on top.
- *
- * Encryption: `posthog_integration.sensitive_config` is a Django
- * `EncryptedJSONField`, which `EncryptedFieldMixin.get_internal_type`
- * declares as TEXT in PG. So the on-disk format matches
- * `agent_application.encrypted_env` — Fernet ciphertext, base64 ASCII.
- * `EncryptedFields.decryptJson` handles the round-trip.
- */
-
-import type { Pool } from 'pg'
-
-import { EncryptedFields } from '../runtime/encryption'
-import { IntegrationCredentials } from '../spec/tool'
-
-export interface IntegrationRow {
- integration_id: string
- credentials: IntegrationCredentials
-}
-
-export interface IntegrationStore {
- /**
- * One row by natural key. Returns null when no row exists or the row's
- * sensitive_config can't be decrypted (key rotated past it, ignored on
- * the Python side via `ignore_decrypt_errors=True`).
- */
- get(team_id: number, kind: string, integration_id: string): Promise<IntegrationCredentials | null>
- /**
- * Every connected integration of one kind for one team. Most teams have
- * exactly one row per kind; multiples happen when a team connects two
- * Slack workspaces (etc.). Tools that take an explicit `team_integration_id`
- * use this list to find the right row.
- */
- list(team_id: number, kind: string): Promise<IntegrationRow[]>
- /**
- * Resolve every kind declared in a spec to its credentials map, keyed by
- * `<kind>:<integration_id>`. This is the shape `ToolContext.integrations`
- * expects — see the existing harness fixture in
- * services/agent-tests/src/cases/example-sre-bot.test.ts. Missing kinds
- * are silently omitted; the tool surfaces "integration not connected"
- * at call time.
- */
- resolveForSpec(team_id: number, specIntegrations: string[]): Promise<Record<string, IntegrationCredentials>>
-}
-
-function parseSensitiveConfig(raw: Record<string, unknown> | null, kind: string): IntegrationCredentials | null {
- if (!raw) {
- return null
- }
- const access_token = typeof raw.access_token === 'string' ? raw.access_token : ''
- if (!access_token) {
- // A row without an access token is unusable for the tool runtime; the
- // runner / ingress treat it like a missing integration.
- return null
- }
- const credentials: IntegrationCredentials = { kind, access_token }
- if (typeof raw.refresh_token === 'string') {
- credentials.refresh_token = raw.refresh_token
- }
- // Capture everything else under metadata so tools that need workspace ids
- // or scopes can read them without a second query.
- const metadata: Record<string, unknown> = {}
- for (const [k, v] of Object.entries(raw)) {
- if (k === 'access_token' || k === 'refresh_token') {
- continue
- }
- metadata[k] = v
- }
- if (Object.keys(metadata).length > 0) {
- credentials.metadata = metadata
- }
- return credentials
-}
-
-interface DbRow {
- integration_id: string | null
- sensitive_config: string | null
-}
-
-export class PgIntegrationStore implements IntegrationStore {
- constructor(
- private readonly pool: Pool,
- private readonly encryption: EncryptedFields
- ) {}
-
- async get(team_id: number, kind: string, integration_id: string): Promise<IntegrationCredentials | null> {
- const r = await this.pool.query<DbRow>(
- `SELECT integration_id, sensitive_config::text AS sensitive_config
- FROM posthog_integration
- WHERE team_id = $1 AND kind = $2 AND integration_id = $3
- LIMIT 1`,
- [team_id, kind, integration_id]
- )
- if (r.rowCount === 0) {
- return null
- }
- return this.decryptRow(kind, r.rows[0])
- }
-
- async list(team_id: number, kind: string): Promise<IntegrationRow[]> {
- const r = await this.pool.query<DbRow>(
- `SELECT integration_id, sensitive_config::text AS sensitive_config
- FROM posthog_integration
- WHERE team_id = $1 AND kind = $2
- ORDER BY integration_id`,
- [team_id, kind]
- )
- const out: IntegrationRow[] = []
- for (const row of r.rows) {
- if (!row.integration_id) {
- continue
- }
- const credentials = this.decryptRow(kind, row)
- if (credentials) {
- out.push({ integration_id: row.integration_id, credentials })
- }
- }
- return out
- }
-
- async resolveForSpec(team_id: number, kinds: string[]): Promise<Record<string, IntegrationCredentials>> {
- if (kinds.length === 0) {
- return {}
- }
- const r = await this.pool.query<{
- kind: string
- integration_id: string | null
- sensitive_config: string | null
- }>(
- `SELECT kind, integration_id, sensitive_config::text AS sensitive_config
- FROM posthog_integration
- WHERE team_id = $1 AND kind = ANY($2::text[])`,
- [team_id, kinds]
- )
- const out: Record<string, IntegrationCredentials> = {}
- for (const row of r.rows) {
- if (!row.integration_id) {
- continue
- }
- const credentials = this.decryptRow(row.kind, row)
- if (credentials) {
- out[`${row.kind}:${row.integration_id}`] = credentials
- }
- }
- return out
- }
-
- private decryptRow(kind: string, row: DbRow): IntegrationCredentials | null {
- if (!row.sensitive_config) {
- return null
- }
- try {
- const decoded = this.encryption.decryptJson(row.sensitive_config)
- return parseSensitiveConfig(decoded, kind)
- } catch {
- return null
- }
- }
-}
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts
index fb820ea22c46..8c9251a9906a 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-impls.test.ts
@@ -13,11 +13,9 @@ import { Pool } from 'pg'
import { isReachable, reset } from '@posthog/agent-shared/testing'
-import { EncryptedFields } from '../runtime/encryption'
import { PgSandboxInstanceStore } from '../sandbox/sandbox-instance-store'
import { AgentSpecSchema, AssistantMessageRecord, EMPTY_USAGE_TOTAL } from '../spec/spec'
import { hashCanonicalArgs } from './approval-store'
-import { PgIntegrationStore } from './integration-store'
import { PgApprovalStore } from './pg-approval-store'
import { PgSessionQueue } from './pg-queue'
import { PgRevisionStore } from './pg-revision-store'
@@ -768,70 +766,6 @@ maybeDescribe('Postgres impls (real PG)', () => {
expect(all.length).toBeGreaterThanOrEqual(3)
})
- it('PgIntegrationStore reads + decrypts posthog_integration rows', async () => {
- if (!reachable) {
- return
- }
- // The test DB is the runtime queue DB which @posthog/agent-migrations
- // owns. posthog_integration lives in the main posthog DB in prod;
- // we recreate a minimal slice here so the store has something to
- // read from. Mirrors the existing harness pattern for agent_revision.
- await pool.query(`
- CREATE TABLE IF NOT EXISTS posthog_integration (
- id BIGSERIAL PRIMARY KEY,
- team_id INTEGER NOT NULL,
- kind TEXT NOT NULL,
- integration_id TEXT NOT NULL,
- sensitive_config TEXT,
- config JSONB DEFAULT '{}'::jsonb
- )
- `)
- await pool.query('TRUNCATE posthog_integration')
-
- // Fernet keys must base64url-decode to 32 bytes. EncryptedFields
- // base64-encodes the raw UTF-8 string, so we pass 32 ASCII chars.
- const encryption = new EncryptedFields('01234567890123456789012345678901')
- const slackBlob = encryption.encrypt(
- JSON.stringify({ access_token: 'xoxb-acme', refresh_token: 'r1', scopes: ['chat:write'] })
- )
- const githubBlob = encryption.encrypt(JSON.stringify({ access_token: 'gh_acme' }))
- await pool.query(
- `INSERT INTO posthog_integration (team_id, kind, integration_id, sensitive_config)
- VALUES (7, 'slack', 'T01ACME', $1),
- (7, 'github', 'acme-org', $2)`,
- [slackBlob, githubBlob]
- )
-
- const store = new PgIntegrationStore(pool, encryption)
-
- // Direct lookup by natural key returns decrypted credentials.
- const slack = await store.get(7, 'slack', 'T01ACME')
- expect(slack?.access_token).toBe('xoxb-acme')
- expect(slack?.refresh_token).toBe('r1')
- expect(slack?.metadata).toEqual({ scopes: ['chat:write'] })
-
- // Missing rows return null.
- expect(await store.get(7, 'slack', 'NOT_THERE')).toBeNull()
- expect(await store.get(99, 'slack', 'T01ACME')).toBeNull()
-
- // resolveForSpec returns a `<kind>:<integration_id>`-keyed map.
- const map = await store.resolveForSpec(7, ['slack', 'github', 'linear'])
- expect(Object.keys(map).sort()).toEqual(['github:acme-org', 'slack:T01ACME'])
- expect(map['github:acme-org'].access_token).toBe('gh_acme')
-
- // Rows with undecodable sensitive_config (corrupted ciphertext, key
- // rotated past it) are silently omitted, mirroring Django's
- // ignore_decrypt_errors behaviour. The store doesn't crash the
- // resolver path.
- await pool.query(
- `INSERT INTO posthog_integration (team_id, kind, integration_id, sensitive_config)
- VALUES (7, 'slack', 'T02BAD', $1)`,
- ['gAAAAA-not-a-real-token']
- )
- const slacks = await store.list(7, 'slack')
- expect(slacks.map((r) => r.integration_id).sort()).toEqual(['T01ACME'])
- })
-
// ------------------------------------------------------------------
// Idempotency-key guarantees
//
diff --git a/products/agent_platform/services/agent-shared/src/runtime/credential-broker.ts b/products/agent_platform/services/agent-shared/src/runtime/credential-broker.ts
index bb6daea3ec3d..f6e4dd600ca8 100644
--- a/products/agent_platform/services/agent-shared/src/runtime/credential-broker.ts
+++ b/products/agent_platform/services/agent-shared/src/runtime/credential-broker.ts
@@ -48,13 +48,6 @@ export type Credential =
* (e.g. to call back into the issuing system) or read `claims`.
*/
| { kind: 'jwt'; token: string; claims: Record<string, unknown> }
- /**
- * Reference to a team-level integration credential (Slack token,
- * etc.). The runner resolves to the actual access token through the
- * existing `IntegrationCredentials` resolver — keeping the integration
- * shape consistent with native-tool usage today.
- */
- | { kind: 'integration_ref'; integration_id: string }
/**
* Map of target → credential. Targets are author-defined strings; the
diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.test.ts b/products/agent_platform/services/agent-shared/src/spec/spec.test.ts
index 2a56d28aadc6..309ac380c689 100644
--- a/products/agent_platform/services/agent-shared/src/spec/spec.test.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/spec.test.ts
@@ -30,7 +30,6 @@ describe('AgentSpecSchema', () => {
],
mcps: [{ id: 'posthog', url: 'https://app.posthog.com/api/mcp' }],
skills: [{ id: 'deep-research', path: 'skills/deep-research/SKILL.md' }],
- integrations: ['slack:T01'],
secrets: ['ACME_KEY'],
limits: { max_turns: 10, max_tool_calls: 50, max_wall_seconds: 300 },
entrypoint: 'agent.md',
@@ -408,7 +407,6 @@ describe('AgentSpecSchema', () => {
{
id: 'linear',
url: 'https://mcp.linear.app/sse',
- auth: { integration: 'linear:T01' },
secrets: ['LINEAR_TOKEN'],
tools: ['create-issue', 'list-issues'],
},
@@ -417,7 +415,6 @@ describe('AgentSpecSchema', () => {
const m = spec.mcps[0]
expect(m.id).toBe('linear')
expect(m.url).toBe('https://mcp.linear.app/sse')
- expect(m.auth?.integration).toBe('linear:T01')
expect(m.secrets).toEqual(['LINEAR_TOKEN'])
expect(m.tools).toEqual(['create-issue', 'list-issues'])
})
diff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.ts
index bc9efe7d98ad..c2a7b79e23f2 100644
--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts
@@ -494,95 +494,90 @@ export const McpToolEntrySchema = z.union([
* the open client.
*
* Single shape today: a third-party MCP server reachable over HTTP.
- * `auth.integration` plugs into PostHog's integrations registry (OAuth-style);
- * `secrets[]` is the simpler per-MCP token case, resolved through the same
- * encrypted-env path the agent's main `spec.secrets` uses. `id` is the tool-
- * name prefix. `tools[]` selects + gates: bare string = inclusion only; object
- * form adds `requires_approval` + `approval_policy`.
+ * `auth.provider` references a `spec.identity_providers[]` entry — a
+ * per-principal OAuth identity, stamped as the asker's bearer (gates into
+ * auth_required if unlinked). `secrets[]` + `headers` is the simpler
+ * bring-your-own-token case, resolved through the same encrypted-env path the
+ * agent's main `spec.secrets` uses. `id` is the tool-name prefix. `tools[]`
+ * selects + gates: bare string = inclusion only; object form adds
+ * `requires_approval` + `approval_policy`.
*
* The `kind: 'agent'` variant (agent-to-agent MCP composability) was removed
* in favour of a single flat shape — `agent-as-mcp-server.md` will re-add it
* when a concrete consumer lands.
*/
-export const McpRefSchema = z
- .object({
- /**
- * Stable id within the spec. Tool-name prefix at runtime —
- * `<id>__<toolName>` is what the model sees so it can tell which MCP
- * a tool came from. Must be unique across `spec.mcps[]`.
- */
- id: z.string().min(1),
- url: z.string().url(),
- auth: z
- .object({
- /** Team-level integration credential (shared across the team). */
- integration: z.string().optional(),
- /** Per-principal identity provider: stamps the linked user's bearer,
- * gates into auth_required if unlinked. Vs the team-wide `integration`. */
- provider: z.string().optional(),
- })
- .optional(),
- /**
- * Per-MCP secret names. Resolved at session start through the same
- * encrypted-env path as the agent's main `spec.secrets`. The runner
- * substitutes `${name}` placeholders in the URL + auth headers before
- * opening the client; the plaintext never leaves the runner process.
- */
- secrets: z.array(z.string()).default([]),
- /**
- * Author-supplied request headers stamped on every outgoing MCP request.
- * Values may reference `${NAME}` from `secrets[]`; the runner substitutes
- * the plaintext value before opening the MCP client, so the secret never
- * leaves the runner process. Same substitution shape as
- * `@posthog/http-request`'s `headers` — the parallel is intentional so
- * authors can use the same mental model for "bring my own bearer token"
- * against either a typed MCP catalog or a raw HTTP API.
- *
- * Use this for the bring-your-own-token case (paste a PAT once, reference
- * it as `${TOKEN}` in `Authorization: 'Bearer ${TOKEN}'`). For platform-
- * managed OAuth tokens, use `auth.integration` instead; integration-
- * stamped headers compose with author-supplied headers — explicit
- * author entries win on duplicate keys, matching `http-request`'s
- * "caller-set values are not silently overwritten" rule.
- */
- headers: z.record(z.string(), z.string()).optional(),
- /**
- * Per-tool selection AND approval gating. Bare string is a passthrough
- * (gates inclusion, no approval); object form carries
- * `requires_approval` + `approval_policy`. Omitted / empty = expose
- * every tool the server lists. Replaces the earlier `allowlist[]`
- * field (PR 7 hard-break — no production specs used it).
- *
- * Names must be unique within the array. A duplicate would be a
- * silent first-match-wins footgun — e.g. an author who appends a
- * gated copy of an already-listed bare-string entry would see the
- * gated version ignored. Better to reject at parse time.
- */
- tools: z
- .array(McpToolEntrySchema)
- .optional()
- .refine(
- (entries) => {
- if (!entries) {
- return true
- }
- const seen = new Set<string>()
- for (const e of entries) {
- const name = typeof e === 'string' ? e : e.name
- if (seen.has(name)) {
- return false
- }
- seen.add(name)
- }
+export const McpRefSchema = z.object({
+ /**
+ * Stable id within the spec. Tool-name prefix at runtime —
+ * `<id>__<toolName>` is what the model sees so it can tell which MCP
+ * a tool came from. Must be unique across `spec.mcps[]`.
+ */
+ id: z.string().min(1),
+ url: z.string().url(),
+ auth: z
+ .object({
+ /** Per-principal identity provider (id from `spec.identity_providers[]`):
+ * stamps the linked user's bearer, gates into auth_required if unlinked. */
+ provider: z.string().optional(),
+ })
+ .optional(),
+ /**
+ * Per-MCP secret names. Resolved at session start through the same
+ * encrypted-env path as the agent's main `spec.secrets`. The runner
+ * substitutes `${name}` placeholders in the URL + auth headers before
+ * opening the client; the plaintext never leaves the runner process.
+ */
+ secrets: z.array(z.string()).default([]),
+ /**
+ * Author-supplied request headers stamped on every outgoing MCP request.
+ * Values may reference `${NAME}` from `secrets[]`; the runner substitutes
+ * the plaintext value before opening the MCP client, so the secret never
+ * leaves the runner process. Same substitution shape as
+ * `@posthog/http-request`'s `headers` — the parallel is intentional so
+ * authors can use the same mental model for "bring my own bearer token"
+ * against either a typed MCP catalog or a raw HTTP API.
+ *
+ * Use this for the bring-your-own-token case (paste a PAT once, reference
+ * it as `${TOKEN}` in `Authorization: 'Bearer ${TOKEN}'`). For OAuth, use
+ * `auth.provider` instead; provider-stamped headers compose with
+ * author-supplied headers — explicit author entries win on duplicate
+ * keys, matching `http-request`'s "caller-set values are not silently
+ * overwritten" rule.
+ */
+ headers: z.record(z.string(), z.string()).optional(),
+ /**
+ * Per-tool selection AND approval gating. Bare string is a passthrough
+ * (gates inclusion, no approval); object form carries
+ * `requires_approval` + `approval_policy`. Omitted / empty = expose
+ * every tool the server lists. Replaces the earlier `allowlist[]`
+ * field (PR 7 hard-break — no production specs used it).
+ *
+ * Names must be unique within the array. A duplicate would be a
+ * silent first-match-wins footgun — e.g. an author who appends a
+ * gated copy of an already-listed bare-string entry would see the
+ * gated version ignored. Better to reject at parse time.
+ */
+ tools: z
+ .array(McpToolEntrySchema)
+ .optional()
+ .refine(
+ (entries) => {
+ if (!entries) {
return true
- },
- { message: 'mcps[].tools[] entries must have unique names' }
- ),
- })
- .refine((m) => !(m.auth?.integration && m.auth?.provider), {
- message: 'mcps[].auth cannot set both integration (team-wide) and provider (per-asker)',
- path: ['auth'],
- })
+ }
+ const seen = new Set<string>()
+ for (const e of entries) {
+ const name = typeof e === 'string' ? e : e.name
+ if (seen.has(name)) {
+ return false
+ }
+ seen.add(name)
+ }
+ return true
+ },
+ { message: 'mcps[].tools[] entries must have unique names' }
+ ),
+})
export const SkillRefSchema = z.object({
id: z.string(),
@@ -782,7 +777,6 @@ export const AgentSpecSchema = z.object({
tools: z.array(ToolRefSchema).default([]),
mcps: z.array(McpRefSchema).default([]),
skills: z.array(SkillRefSchema).default([]),
- integrations: z.array(z.string()).default([]),
/** Identity providers users can link against (the credential axis). */
identity_providers: z.array(IdentityProviderConfigSchema).default([]),
secrets: z.array(SecretRefSchema).default([]),
@@ -830,8 +824,8 @@ export function secretRefName(ref: SecretRef): string {
* - `undefined` when the name isn't declared in `spec.secrets[]` at all.
*
* The three-way return is load-bearing: the runtime treats `null` (declared
- * but unbound) as "fail-closed" — same shape as `mcp-clients.ts` refuses an
- * `auth.integration` ref when its host validator isn't wired.
+ * but unbound) as "fail-closed" — a bare-string secret can't be substituted
+ * into an outbound request until it's pinned to an allowed host.
*/
export function getSecretAllowedHosts(spec: AgentSpec, name: string): readonly string[] | null | undefined {
for (const ref of spec.secrets) {
diff --git a/products/agent_platform/services/agent-shared/src/spec/tool.ts b/products/agent_platform/services/agent-shared/src/spec/tool.ts
index 62370dc38735..5e205f2d4b3b 100644
--- a/products/agent_platform/services/agent-shared/src/spec/tool.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/tool.ts
@@ -53,8 +53,6 @@ export interface ToolContext {
/** The agent (application) running this session — the memory scope key. */
applicationId: string
sessionId: string
- /** Resolved integration tokens, keyed by integration id ("slack:T01..."). */
- integrations: Record<string, IntegrationCredentials>
/** Fetch resolved secret value for a name from spec.secrets. */
secret(name: string): string | undefined
/**
@@ -64,9 +62,7 @@ export interface ToolContext {
* UNBOUND — `@posthog/http-request` refuses substitution).
* - `undefined` when the name isn't declared in `spec.secrets[]` at all.
*
- * Fail-closed by design: the bare-string `null` return is the same shape
- * as `mcp-clients.ts` refusing an `auth.integration` ref when its host
- * validator isn't wired. Authors who want to call out to a service with
+ * Fail-closed by design: an author who wants to call out to a service with
* a secret MUST pin that secret to the destination host(s) — a prompt-
* injected `${TOKEN}` against an attacker URL then refuses before fetch
* rather than leaking the credential.
@@ -152,13 +148,6 @@ export interface ToolContext {
posthogApiBaseUrl: string
}
-export interface IntegrationCredentials {
- kind: string
- access_token: string
- refresh_token?: string
- metadata?: Record<string, unknown>
-}
-
/** Outcome of `ctx.identity.resolve`: a usable credential, a link to send, or no-go.
* `allowedHosts` bounds where the bearer may be sent (SSRF guard). */
export type IdentityResolution =
diff --git a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts
index 0ee6ad2b1a83..353777fc243f 100644
--- a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts
+++ b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts
@@ -87,7 +87,6 @@ export const TypedSpecSchema = z
triggers: z.array(z.unknown()).optional(),
mcps: z.array(z.unknown()).optional(),
identity_providers: z.array(z.unknown()).optional(),
- integrations: z.array(z.string()).optional(),
secrets: z.array(z.string()).optional(),
limits: z.unknown().optional(),
auth: z.unknown().optional(),
diff --git a/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts b/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts
index 5d36b5252b15..aba78498b8f7 100644
--- a/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/identity-fetch-tool.test.ts
@@ -104,7 +104,6 @@ maybeDescribe('@posthog/identity-fetch × dogs (real PG + HTTP)', () => {
teamId: 1,
applicationId,
sessionId: randomUUID(),
- integrations: {},
secret: () => undefined,
secretAllowedHosts: () => undefined,
log: () => undefined,
@@ -151,7 +150,6 @@ maybeDescribe('@posthog/identity-fetch × dogs (real PG + HTTP)', () => {
teamId: 1,
applicationId: randomUUID(),
sessionId: randomUUID(),
- integrations: {},
secret: () => undefined,
secretAllowedHosts: () => undefined,
log: () => undefined,
@@ -198,7 +196,6 @@ maybeDescribe('@posthog/identity-fetch × dogs (real PG + HTTP)', () => {
teamId: 1,
applicationId,
sessionId: randomUUID(),
- integrations: {},
secret: () => undefined,
secretAllowedHosts: () => undefined,
log: () => undefined,
diff --git a/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.ts b/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.ts
index cde45ab25597..ea8294f29898 100644
--- a/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.ts
+++ b/products/agent_platform/services/agent-tests/src/cases/per-agent-model.test.ts
@@ -106,7 +106,6 @@ describe('per-agent spec.model resolution: real e2e', () => {
broker: new SecretBroker(),
approvals: new PgApprovalStore(pool),
bus,
- resolveIntegrations: async () => ({}),
resolveSecrets: async () => ({}),
// Per-agent model resolution — keys off spec.model verbatim. This is
// the seam the driver streams with, so recording here proves routing.
diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json
index 59183e2c4ed0..d88586f32253 100644
--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json
+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json
@@ -348,7 +348,6 @@
"description": "Hard rules \u2014 what the Agent Builder MUST NOT do regardless of user request. Load IMMEDIATELY if a request feels like it crosses into raw-secret handling, unprompted promotion, irreversible deletion, or impersonation of another user."
}
],
- "integrations": [],
"identity_providers": [
{
"kind": "posthog",
diff --git a/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json
index 3ba2d2497200..e71570f52ba4 100644
--- a/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json
+++ b/products/agent_platform/services/agent-tests/src/examples/posthog-ai/spec.json
@@ -22,7 +22,6 @@
}
],
"skills": [],
- "integrations": [],
"identity_providers": [
{
"kind": "posthog",
diff --git a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json
index 293507fddd4f..b2d6a7e9fffa 100644
--- a/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json
+++ b/products/agent_platform/services/agent-tests/src/examples/sre-slack-bot/spec.json
@@ -178,7 +178,6 @@
"description": "The runbook corpus in agent memory \u2014 the folder taxonomy (runbooks/alerts, runbooks/systems, runbooks/procedures), how to read it during triage, how to write a GOOD runbook entry, and the approval-gated flow for proposing a new or updated runbook on a user's behalf. ALWAYS load before reading or proposing any change to a runbook \u2014 i.e. at the start of triage (to consult) and after a resolution (to capture the lesson)."
}
],
- "integrations": [],
"limits": {
"max_turns": 30,
"max_tool_calls": 100,
diff --git a/products/agent_platform/services/agent-tests/src/harness/cluster.ts b/products/agent_platform/services/agent-tests/src/harness/cluster.ts
index afab4babebf3..3f4ced012f71 100644
--- a/products/agent_platform/services/agent-tests/src/harness/cluster.ts
+++ b/products/agent_platform/services/agent-tests/src/harness/cluster.ts
@@ -30,7 +30,7 @@ import request from 'supertest'
import { AuthProvider, buildApp, SessionEventBus } from '@posthog/agent-ingress'
import { buildJanitorApp } from '@posthog/agent-janitor'
-import { IntegrationHostValidator, McpTransportFactory, Worker } from '@posthog/agent-runner'
+import { McpTransportFactory, Worker } from '@posthog/agent-runner'
import type { AnalyticsEvent, IdentityStore, LogEntry } from '@posthog/agent-shared'
import {
AgentApplication,
@@ -234,10 +234,6 @@ export interface BuildClusterOpts {
slackSigningSecretResolver?: SecretResolver
/** Override the per-session secret resolver (defaults to empty). */
resolveSecrets?: (sessionId: string) => Promise<Record<string, string>>
- /** Override the per-session integrations resolver (defaults to empty). */
- resolveIntegrations?: (
- sessionId: string
- ) => Promise<Record<string, { kind: string; access_token: string; refresh_token?: string }>>
authProvider?: AuthProvider
/**
* Optional initial script for the faux provider. Tests that script per-test
@@ -257,13 +253,6 @@ export interface BuildClusterOpts {
* `cases/mcp-tools.test.ts`.
*/
mcpTransportFactory?: McpTransportFactory
- /**
- * Gates the `auth.integration` bearer attachment on `external` MCP refs.
- * Defaults to a permissive `() => true` so the common e2e cases don't
- * have to think about it; security-flavoured tests pass a stricter
- * implementation to exercise the rejection paths.
- */
- integrationHostValidator?: IntegrationHostValidator
/**
* Substitute the outbound HTTP client the runner threads into
* `ToolContext.http`. Tests that want to assert on outbound headers
@@ -424,7 +413,6 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
bus,
logs: logSink,
analytics: analyticsSink,
- resolveIntegrations: opts.resolveIntegrations ? async (s) => opts.resolveIntegrations!(s.id) : async () => ({}),
resolveSecrets: opts.resolveSecrets ? async (s) => opts.resolveSecrets!(s.id) : async () => ({}),
resolveModel: resolveModelForHarness,
approvals,
@@ -432,10 +420,6 @@ export async function buildCluster(opts: BuildClusterOpts = {}): Promise<Cluster
memoryStore,
tabularStore,
mcpTransportFactory: opts.mcpTransportFactory,
- // Permissive default so the common e2e suite doesn't have to know
- // about the security gate; the runtime-mcps cases that specifically
- // exercise integration auth (none in the suite yet) can override.
- integrationHostValidator: opts.integrationHostValidator ?? (() => true),
maxConcurrency: 1, // tests prefer serial for deterministic state checks
// Real HttpClient with no proxy by default — tests that exercise
// outbound HTTP hit real localhost servers (matches the wider harness
diff --git a/products/agent_platform/services/agent-tools/src/test-helpers.ts b/products/agent_platform/services/agent-tools/src/test-helpers.ts
index febf71c3a7fc..046898f965bb 100644
--- a/products/agent_platform/services/agent-tools/src/test-helpers.ts
+++ b/products/agent_platform/services/agent-tools/src/test-helpers.ts
@@ -8,7 +8,6 @@ export function makeCtx(overrides?: Partial<ToolContext>): ToolContext {
teamId: 1,
applicationId: 'test-app',
sessionId: 'test-session',
- integrations: {},
secret: (_name: string) => undefined,
secretAllowedHosts: (_name: string) => undefined,
log: (level, msg, meta) => {
@@ -30,7 +29,6 @@ export function makeCapturingCtx(): {
teamId: 1,
applicationId: 'test-app',
sessionId: 'test-session',
- integrations: {},
secret: () => undefined,
secretAllowedHosts: () => undefined,
log: (level, msg, meta) => {
diff --git a/products/agent_platform/services/agent-tools/src/tools/memory.test.ts b/products/agent_platform/services/agent-tools/src/tools/memory.test.ts
index 44bf2ea6835a..cd87c596444d 100644
--- a/products/agent_platform/services/agent-tools/src/tools/memory.test.ts
+++ b/products/agent_platform/services/agent-tools/src/tools/memory.test.ts
@@ -22,7 +22,6 @@ function makeCtx(store: S3MemoryStore | undefined): ToolContext {
teamId: 42,
applicationId: 'app-test',
sessionId: 'sess-1',
- integrations: {},
secret: () => undefined,
secretAllowedHosts: () => undefined,
log: () => undefined,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9d7c341ffd66..227fbacf7803 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8207,7 +8207,6 @@ export namespace Schemas {
};
export type AgentRevisionSpecMcpsItemAuth = {
- integration?: string;
provider?: string;
};
@@ -8359,7 +8358,6 @@ export namespace Schemas {
tools: AgentRevisionSpecToolsItem[];
mcps: AgentRevisionSpecMcpsItem[];
skills: AgentRevisionSpecSkillsItem[];
- integrations: string[];
identity_providers?: AgentRevisionSpecIdentityProvidersItem[];
secrets: AgentRevisionSpecSecretsItem[];
limits: AgentRevisionSpecLimits;
@@ -34185,7 +34183,6 @@ export namespace Schemas {
};
export type PatchedAgentRevisionSpecMcpsItemAuth = {
- integration?: string;
provider?: string;
};
@@ -34337,7 +34334,6 @@ export namespace Schemas {
tools: PatchedAgentRevisionSpecToolsItem[];
mcps: PatchedAgentRevisionSpecMcpsItem[];
skills: PatchedAgentRevisionSpecSkillsItem[];
- integrations: string[];
identity_providers?: PatchedAgentRevisionSpecIdentityProvidersItem[];
secrets: PatchedAgentRevisionSpecSecretsItem[];
limits: PatchedAgentRevisionSpecLimits;
diff --git a/services/mcp/src/generated/agent_platform/api.ts b/services/mcp/src/generated/agent_platform/api.ts
index 6a3b6a4aed85..eee84b7d10f8 100644
--- a/services/mcp/src/generated/agent_platform/api.ts
+++ b/services/mcp/src/generated/agent_platform/api.ts
@@ -218,7 +218,6 @@ export const agentApplicationsRevisionsCreateBodySpecMcpsDefault = []
export const agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin = 0
export const agentApplicationsRevisionsCreateBodySpecSkillsDefault = []
-export const agentApplicationsRevisionsCreateBodySpecIntegrationsDefault = []
export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneIdDefault = `posthog`
export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneBindingDefault = `principal`
@@ -584,7 +583,6 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
url: zod.url(),
auth: zod
.object({
- integration: zod.string().optional(),
provider: zod.string().optional(),
})
.optional(),
@@ -650,7 +648,6 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({
})
)
.default(agentApplicationsRevisionsCreateBodySpecSkillsDefault),
- integrations: zod.array(zod.string()).default(agentApplicationsRevisionsCreateBodySpecIntegrationsDefault),
identity_providers: zod
.array(
zod.union([
@@ -906,7 +903,6 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin = 0
export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault = []
-export const agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault = []
export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneIdDefault = `posthog`
export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneBindingDefault = `principal`
@@ -1288,7 +1284,6 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
url: zod.url(),
auth: zod
.object({
- integration: zod.string().optional(),
provider: zod.string().optional(),
})
.optional(),
@@ -1354,9 +1349,6 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.o
})
)
.default(agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault),
- integrations: zod
- .array(zod.string())
- .default(agentApplicationsRevisionsPartialUpdateBodySpecIntegrationsDefault),
identity_providers: zod
.array(
zod.union([
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json
index 47c87a9b78ae..aa919c94c299 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json
@@ -134,13 +134,6 @@
},
"type": "array"
},
- "integrations": {
- "default": [],
- "items": {
- "type": "string"
- },
- "type": "array"
- },
"limits": {
"default": {
"max_cpu_cores": 0.25,
@@ -194,9 +187,6 @@
"properties": {
"auth": {
"properties": {
- "integration": {
- "type": "string"
- },
"provider": {
"type": "string"
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json
index b3a203ec0110..dd7d6b2dca4c 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json
@@ -137,13 +137,6 @@
},
"type": "array"
},
- "integrations": {
- "default": [],
- "items": {
- "type": "string"
- },
- "type": "array"
- },
"limits": {
"default": {
"max_cpu_cores": 0.25,
@@ -197,9 +190,6 @@
"properties": {
"auth": {
"properties": {
- "integration": {
- "type": "string"
- },
"provider": {
"type": "string"
}