930aaeb
CopilotKitDocs
  • Docs
  • Integrations
  • Reference
Get Started
QuickstartCoding Agents
Concepts
ArchitectureGenerative UI OverviewOSS vs Enterprise
Agentic Protocols
OverviewAG-UIAG-UI MiddlewareMCPA2A
Build Chat UIs
Prebuilt Components
CopilotChatCopilotSidebarCopilotPopup
Custom Look and Feel
CSS CustomizationSlots (Subcomponents)Fully Headless UIReasoning Messages
Multimodal AttachmentsVoice
Build Generative UI
Controlled
Tool-based Generative UITool RenderingState RenderingReasoning
Your Components
Display ComponentsInteractive Components
Declarative
A2UIDynamic Schema A2UIFixed Schema A2UI
Open-Ended
MCP Apps
Adding Agent Powers
Frontend ToolsShared State
Human-in-the-Loop
HITL OverviewPausing the Agent for InputHeadless Interrupts
Sub-AgentsAgent ConfigProgrammatic Control
Agents & Backends
Built-in Agent
Backend
Copilot RuntimeFactory ModeAG-UI
Runtime Server AdapterAuthentication
AG2
Shared state
Reading agent stateWriting agent state
Readables
Observe & Operate
InspectorVS Code Extension
Troubleshooting
Common Copilot IssuesError Debugging & ObservabilityDebug ModeAG-UI Event InspectorHook ExplorerError Observability Connectors
Enterprise
CopilotKit PremiumHow the Enterprise Intelligence Platform WorksHow Threads & Persistence WorkObservabilitySelf-Hosting IntelligenceThreads
Deploy
AWS AgentCore
What's New
Full MCP Apps SupportLangGraph Deep Agents in CopilotKitA2UI Launches with full AG-UI SupportCopilotKit v1.50Generative UI Spec SupportA2A and MCP Handshake
Migrate
Migrate to V2Migrate to 1.8.2
Other
Contributing
Code ContributionsDocumentation Contributions
Anonymous Telemetry
AG2Agentic ProtocolsAG-UI Middleware

AG-UI Middleware

Configure AG-UI middleware for your CopilotKit application.

AG-UI middleware is fundamentally an AG-UI protocol concept defined upstream in @ag-ui/client. This page covers how to wire it into a CopilotKit runtime; for the protocol-level reference (lifecycle, runNextWithState, the Middleware base class), see the upstream guide at docs.ag-ui.com/sdk/js/client/middleware.

AG-UI agents expose a middleware layer via agent.use(middleware), a powerful hook for logging, guardrails, request transformation, and event rewriting. Because CopilotKit runs the middleware server-side inside the Copilot Runtime, it executes in a trusted environment where the client cannot tamper with it.

Defining a Middleware#

A middleware extends the Middleware base class from @ag-ui/client and implements run(input, next). It receives the incoming RunAgentInput and returns an Observable<BaseEvent>, typically by subscribing to runNextWithState(input, next) and transforming the stream:

import {
  Middleware,
  RunAgentInput,
  AbstractAgent,
  BaseEvent,
} from "@ag-ui/client";
import { Observable } from "rxjs";

export class LoggingMiddleware extends Middleware {
  run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent> {
    return new Observable<BaseEvent>((subscriber) => {
      const sub = this.runNextWithState(input, next).subscribe({
        next: ({ event }) => {
          console.log("[agent event]", event.type);
          subscriber.next(event);
        },
        error: (err) => subscriber.error(err),
        complete: () => subscriber.complete(),
      });
      return () => sub.unsubscribe();
    });
  }
}

Attaching Middleware to an Agent#

Call .use(...) on the agent before registering it with the runtime:

import { CopilotRuntime } from "@copilotkit/runtime";
import { LangGraphAgent } from "@copilotkit/runtime/langgraph";
import { LoggingMiddleware } from "./my-middleware";

const agent = new LangGraphAgent({
  deploymentUrl: process.env.LANGGRAPH_DEPLOYMENT_URL!,
  graphId: "sample_agent",
});
agent.use(new LoggingMiddleware());

const runtime = new CopilotRuntime({
  agents: { default: agent },
});

Built-in Middleware#

The runtime ships first-class middleware options you can enable directly on CopilotRuntime without calling .use() on each agent:

  • a2ui — apply A2UIMiddleware to all (or a subset of) registered agents. See Copilot Runtime → A2UI.
  • mcpApps — configure MCP servers for all agents from a single place. See Copilot Runtime → mcpApps.

Related#

  • Copilot Runtime — the server-side layer that executes middleware.
  • AG-UI Protocol — the event stream the middleware operates on.