# Building MAF AI Agent UIs with Next.js, AG-UI & CopilotKit

Across all the examples and articles published on my blog covering **Microsoft Agent Framework (MAF)** and **Microsoft Foundry** I have extensively used console applications as the client interface.

That's kind of boring and dull from a user experience perspective. Imagine you have built sophisticated agents and workflows and then you present a console based application to the end user.

> An user expects an engaging and an interactive real world interactive user experience and this is what I will try to build in this article using `CopilotKit` and with my limited knowledge on `Next.js` and `React`

So, it's time to move beyond the console !!!

And believe me you don't have to master any JavaScript based web frameworks. With [CopilotKit](https://docs.copilotkit.ai/) you can have a rich web UI up and running in no time.

In this article, we will explore how to build a React-based front end for agents created using Microsoft Agent Framework, bringing together **AG-UI** and **CopilotKit** to create a more interactive and engaging user experience.

### **AG-UI**

The Agent-User Interaction Protocol or commonly known as AG-UI is a protocol developed to expose AI agents to web/mobile frontends.

Think of AG-UI as HTTP protocol for AI Agents. With AG-UI its now possible to call and render tools through agents invoked from your frontends. Before AG-UI all frontend calls to AI agents required custom integration but AG-UI has made it the integration pretty straightforward.

Microsoft Agent Framework (MAF) and AG-UI together offer a clean separation:

- **MAF** handles the agent’s intelligence, workflows, memory, and tool use.
- **AG-UI** is the open protocol that standardizes how agents communicate with user interfaces.

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/c26d8491-393e-4cef-bf06-fcaa6581f16c.png align="center")

*Image Credit : Copilotkit*

For more details on AG-UI implementation , please refer to one of my past article on the topic [here](https://www.azureguru.net/ag-ui-protocol-in-microsoft-agent-framework) .

In the article the AG-UI server invokes two functions:

- **ReturnCityTemperature**
- **ReturnCountryCapital**

The agent is strictly instructed to return only the data provided by these two functions and should not provide any external data as the output on which the model is trained on.

The only difference being that I changed the endpoints in the code from this

```csharp
WebApplication app = builder.Build();      
app.MapAGUI("/", agent);
await app.RunAsync();
```

to

```csharp
  WebApplication app = builder.Build();      
  app.MapAGUI("/ag-ui", agent);
  await app.RunAsync("http://localhost:5000");
```

### So what is CopilotKit ?

CopilotKit is an open-source framework that helps developers integrate AI copilots and agent capabilities directly into their applications.

Instead of the developer building a custom interface for agent interaction and implementing UI updates from scratch CopilotKit provides a reusable React components, hooks, and APIs to simplify this development.

To put in simple words, CopilotKit helps in building the front end of AI-powered applications while our backend agents handle the actual reasoning and execution of tasks and they both communicate through AG-UI.

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/7e9585b2-7fc3-4780-ab7a-2e3994e2fc37.png align="center")

*Image Credit : Copilotkit*

The official Copilotkit documentation can be found [here](https://docs.copilotkit.ai/) .

### SetUp

To get started , create an empty Visual Studio solution file in a new directory. I created with name **CoplitKitApp.**(There is a typo in the directory name.I wanted to name it as **CopilotKitApp** but ended up naming it as **CoplitKitApp** ..lol..)

Navigate to the newly created directory through PowerShell and create a new Next.js application with the following command.

```yaml
npx create-next-app@latest web --typescript --tailwind --eslint --app --src-dir --use-npm
```

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/f05da354-1355-4eb9-a41d-3d43b5921428.png align="center")

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/86e3b986-7207-4d42-aedc-d161f7d2ab41.png align="center")

The `npm` command creates the required files in the web folder of the `Next.js` project

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/4981a297-d541-4827-87d0-ee8cecca44a5.png align="center")

Navigate to the web folder in PowerShell and execute the following command to install the **CopilotKit packages**

```yaml
 npm install @copilotkit/react-core @copilotkit/runtime @ag-ui/client
```

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/e9302eac-3177-4fb6-a129-82486223adec.png align="center")

The command gets the React hooks, pre-built UI components and backend runtime and it also configures the `AG-UI`client.

During the installation you will get a bunch of warning messages.You can ignore them.

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/3550d181-92ba-4821-aade-8b859729ed65.png align="center")

The execution should conclude with the following messages

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/0fe0226c-ad0b-4cdf-8627-cdf0ae3baa40.png align="center")

Once the `CopilotKit` packages are installed ,create a `.env.local` file in the `web` directory and add the `AG-UI` server endpoint to the file.

To do so, open the file in notepad

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/fb36f28c-fb58-4348-b87c-98477467ffa0.png align="center")

In my case the server end point is : `http://localhost:5000/ag-ui`

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/9231ae18-f656-44c6-88b0-1b4af68e8921.png align="center")

So the entry in the `.env.local` file for this example is :

```yaml
MAF_AGENT_URL=http://localhost:5000/ag-ui
```

Now add the web project to the blank Visual Studio that we created earlier.

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/59e6e654-0474-4434-9898-01d07500c099.png align="center")

Next, create a `route.ts` file in the `src` folder in the following path of the project

`src/app/api/copilotkit/[[...slug]]/route.ts`

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p>The underlying folders in the src folders have to create manually. Also note the folder with name in the above path : <code>[[...slug]]</code></p></div>
</div>

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/cb341d05-33a8-4ca1-ac42-08f85990ba7b.png align="center")

**Copilotkit route.ts >>**

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/b53faf44-5838-495e-9310-737cc2874c54.png align="center")

In our example add the following code in `route.ts`

```typescript
import {
  CopilotRuntime,
  createCopilotRuntimeHandler,
} from "@copilotkit/runtime/v2";

import { HttpAgent } from "@ag-ui/client";

const runtime = new CopilotRuntime({
  agents: {
    maf_agent: new HttpAgent({
      url: process.env.MAF_AGENT_URL!,
    }),
  },
});

const handler = createCopilotRuntimeHandler({
  runtime,
  basePath: "/api/copilotkit",
});

export const GET = handler;
export const POST = handler;
```

The above code creates the Next.js API route handler for CopilotKit runtime and exposes the `GET` and `POST` requests and forwards them to CopilotKit runtime.

It also reads from the server URL from the `env` file that we created earlier.

In essence, `route.ts` is the HTTP gateway for CopilotKit in Next.js application.

**Copilotkit providers.tsx >>**

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/f5bfb643-41d0-483a-929b-a5e03946aeef.png align="center")

Create a new file called `providers.tsx` to the `app` folder and add the following code

```typescript
"use client";

import { CopilotKit } from "@copilotkit/react-core/v2";

export function Providers({
    children,
}: {
    children: React.ReactNode;
}) {
    return (
        <CopilotKit runtimeUrl="/api/copilotkit" agent="maf_agent">
            {children}
        </CopilotKit>
    );
}
```

**Copilotkit layout.tsx >>**

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/cb8cc978-4594-4284-a262-e39014c4b32c.png align="center")

Create a new file called `layout.tsx` to the `app` folder and add the following code

```typescript
import type { Metadata } from "next";
import { Providers } from "./providers";

import "@copilotkit/react-core/v2/styles.css";
import "./globals.css";

export const metadata: Metadata = {
    title: "MAF CopilotKit",
    description: "CopilotKit for Microsoft Agent Framework",
};

export default function RootLayout({
    children,
}: Readonly<{
    children: React.ReactNode;
}>) {
    return (
        <html lang="en">
            <body>
                <Providers>
                    {children}
                </Providers>
            </body>
        </html>
    );
}
```

The provider makes CopilotKit available throughout the React application.

**Copilotkit page.tsx >>**

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/0262eb4e-7d59-404e-af48-b76ce6ec89e4.png align="center")

Add a new file called `page.tsx` to the `app` folder and add the following code in it

```typescript
"use client";

import { CopilotChat } from "@copilotkit/react-core/v2";

export default function Home() {
    return (
        <main className="h-screen w-full">
        <h1>My first CoPilotKit app</h1>
         <CopilotSidebar />
         <CopilotChat />          
         </main>
    );
}
```

This component provides the chat interface

So ,the `src` folder structure should look like this

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/86e2f931-3c5b-4cfe-9ccc-7e5a235c0edb.png align="left")

### **Run the application**

First , run the AG-UI server >>

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/2df9c3b5-e69d-434c-bda5-efeff177a955.png align="center")

and then the client >>

Navigate to the web folder. In this example its located in `I:\CoplitKitApp\web` and run `npm run dev`

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/3089addf-c5ec-4bdf-8f92-f93aa1182426.png align="left")

Browsing to `http://localhost:3000/` leads to the chat interface.

Notice the arrow at the bottom left of the screen

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/77095b77-1142-47fe-9f59-e3be058fe9d5.png align="center")

Clicking on it pops up the error message. I am really unsure what this error is about.

![](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/8e82fbdc-2432-4ff8-aace-d966393f58ec.png align="center")

But the error isn't hampering the agent calls.

If you are a Next.js or React developer, it would great if you could provide your insights on how to resolve the error.

### Execution

I have a hosted agent running Foundry based on the same data. The code to the agent running in Foundry is [here](https://www.azureguru.net/deploy-an-ai-agent-leveraging-agent-identity-as-hosted-agent-to-microsoft-foundry#code) which is same as the code I used for my article on AG-UI [here](https://www.azureguru.net/ag-ui-protocol-in-microsoft-agent-framework) .

During the execution , I ran the same prompts simultaneously in this app and also in the hosted agent in Foundry.

![CopilotKit and Microsoft Agent Framework](https://cdn.hashnode.com/uploads/covers/6693c62c166ee9c594cffda0/26d7fd09-c3c4-4942-987b-f9dce81aa37f.gif align="center")

### Conclusion

CopilotKit is an open-source framework for embedding interactive agents directly into web applications (such as React, Next.js, Angular, and Vue).

As demonstrated in this article its relatively very easy to have a rich and interactive web based front end in no time.

So head and give it a try !!!
