withKontext mixin adds Kontext capabilities to any Cloudflare Agent. It handles MCP OAuth, credential storage via Durable Objects, and exposes your integrations as ready-to-use tools.
Install
Complete example
What withKontext adds
withKontext(AgentClass) is a mixin that extends your Agent class with Kontext capabilities. It hooks into the Agent lifecycle automatically:
onConnect— Captures the callback host used for OAuth popup redirects.onStart— Configures the OAuth callback response handler.onRequest— Delegates MCP transport and OAuth callback requests to the built-in MCP handler.
this.kontextTools()— Returns aPromise<ToolSet>with all tools from connected integrations. Call this in message handlers (e.g.onChatMessage) afteronConnecthas fired. On first run,onConnectmust set the callback host beforekontextTools()can connect to Kontext.this.kontextSystemPrompt— A string describing which integrations are connected and available. Pass it to your LLM as the system prompt.this.createMcpOAuthProvider(callbackUrl)— Returns aKontextCloudflareOAuthProviderinstance. ThecallbackUrlparameter is required. Override this method to customize the OAuth provider.
OAuth with Durable Object storage
KontextCloudflareOAuthProvider stores OAuth tokens and session state in Durable Objects. The mixin configures this automatically using your KONTEXT_CLIENT_ID environment variable.
createMcpOAuthProvider() in your agent class:
Wrangler configuration
AddKONTEXT_CLIENT_ID to your wrangler.toml:
Environment bindings
YourEnv type needs to include the Kontext client ID and any Durable Object bindings the SDK uses:
withKontext mixin reads KONTEXT_CLIENT_ID from the environment automatically. No additional configuration is needed beyond setting the variable.
Optionally set KONTEXT_SERVER_URL to point at a non-default Kontext API host.
Using tools with an LLM
Once you have tools fromkontextTools(), pass them to any LLM SDK:
Next steps
- React SDK — Build a frontend that connects to your Cloudflare Agent.
- Vercel AI SDK — Use Kontext tools with
generateTextandstreamText. - How Kontext Works — Understand the Kontext architecture and credential flow.