# Connect and run your agent in Microsoft Teams

> Run any supported agent framework in Teams through a cloud-hosted Intelligence connection.

Run your agent as a Microsoft Teams bot. CopilotKit Intelligence owns the
messaging endpoint and the Teams credentials, and your process owns the agent
and the application logic.

The bot is created in your own Microsoft tenant and belongs to you. Setup
registers it in Teams Developer Portal. No Azure subscription and no Azure Bot
resource are involved. If you approve bots for your tenant, see
[What kind of bot this is](#what-kind-of-bot-this-is).

New to the product? Start with the [Channels overview](/teams) to understand
how the SDK, Runtime, Intelligence, and provider connection fit together.

Before you continue, [configure the Channel in Intelligence](/teams/intelligence).
You should have `CHANNEL_CODE` and `CPK_INTELLIGENCE_API_KEY`.

## Start with your coding agent [#start-with-your-coding-agent]

Use this prompt to connect your agent to Microsoft Teams, start the runner, and verify a real channel message. You can also follow the manual steps below.

<PageAgentPrompt />

## Before you start [#before-you-start]

- Node.js 22 or later; the managed launcher requires the global `WebSocket`
  available in Node.js 22+
- A long-running Node host or container; serverless request handlers cannot own
  the persistent gateway connection

## Build and run your Channel [#build-and-run-your-channel]

<Steps>
  <Step>
    ### Create the runner [#create-the-runner]

    ```bash title="Terminal"
    mkdir my-teams-channel
    cd my-teams-channel
    npm init -y
    npm pkg set type=module
    ```

    Use this tested package combination. Keep exact versions in your lockfile and
    verify compatibility before changing either package.

    ```bash title="Terminal"
    npm install --save-exact @copilotkit/channels@0.11.0 @copilotkit/runtime@1.73.3
    ```

    ```bash title="Terminal"
    npm install -D tsx typescript @types/node
    ```

    ```json title="tsconfig.json"
    {
      "compilerOptions": {
        "target": "ES2022",
        "module": "NodeNext",
        "moduleResolution": "NodeNext",
        "strict": true,
        "skipLibCheck": true,
        "noEmit": true,
        "types": ["node"]
      },
      "include": ["*.ts", "*.tsx"]
    }
    ```

  </Step>

  <Step>
    ### Connect your agent backend [#connect-your-agent-backend]

    The selector's **Agent backend** controls the setup below. It must export a
    fresh `makeAgent(threadId)` result for each Teams conversation.

  </Step>

  <Step>
    ### Declare the managed Teams Channel [#declare-the-managed-teams-channel]

    Create the runner below. Replace `support-teams` with the exact Code shown
    in Intelligence.

    Set `agent: makeAgent` on the Channel because this handler calls
    `thread.runAgent()`. Channels do not inherit `runtime.agents`. A Channel
    whose handlers reply directly without `runAgent()` can omit `agent`.

    ```ts title="channel.ts"
    import { createServer } from "node:http";
    import { createChannel } from "@copilotkit/channels";
    import {
      CopilotKitIntelligence,
      CopilotRuntime,
    } from "@copilotkit/runtime/v2";
    import { createCopilotNodeListener } from "@copilotkit/runtime/v2/node";
    import { makeAgent } from "./agent.js";

    function required(name: string): string {
      const value = process.env[name];
      if (!value) throw new Error(`Missing required environment variable: ${name}`);
      return value;
    }

    const channel = createChannel({
      name: required("CHANNEL_CODE"),
      identifyUser: "platform",
      agent: makeAgent,
    });

    channel.onMessage(async ({ thread, message }) => {
      await thread.runAgent({
        context: [
          { description: "Originating platform", value: message.platform },
        ],
      });
    });

    const intelligence = new CopilotKitIntelligence({
      apiKey: required("CPK_INTELLIGENCE_API_KEY"),
      // Cloud-hosted deployments use the default URLs. Override both URLs
      // together only for self-hosted or non-production Intelligence.
      apiUrl: process.env.INTELLIGENCE_API_URL,
      wsUrl: process.env.INTELLIGENCE_GATEWAY_WS_URL,
    });

    const runtime = new CopilotRuntime({
      agents: {},
      intelligence,
      channels: [channel],
    });

    // Wire teardown before the listener exists, because creating it is what
    // starts the Channel. A Ctrl-C during the connect window then still tears
    // the Channel down instead of hitting Node's default handler.
    let teardown: (() => Promise<void>) | undefined;
    const shutdown = async () => {
      await teardown?.();
    };
    process.once("SIGINT", shutdown);
    process.once("SIGTERM", shutdown);

    const listener = createCopilotNodeListener({
      runtime,
      basePath: "/api/copilotkit",
    });
    const channels = listener.channels;
    const server = createServer(listener);
    teardown = async () => {
      await channels.stop();
      if (server.listening) server.close();
    };

    // Optional: block startup until the activation above settles, so a broken
    // deploy fails loudly instead of serving as a bot that never answers.
    await channels.ready({ timeoutMs: 30_000 });
    const status = channels.status();
    if (status.overall !== "online") {
      throw new Error(`Teams Channel is not online: ${JSON.stringify(status)}`);
    }

    const port = Number(process.env.PORT ?? 3001);
    server.listen(port, () => {
      console.log(`Teams Channel online; lifecycle server listening on :${port}`);
    });
    ```

    Calling `createCopilotNodeListener` starts the Channel. `ready()` is
    optional. It waits until the start settles and throws if it fails.
    `ready()` can settle while setup is still incomplete, so check `status()`
    before you report the Channel online. Without `ready()`, start failures
    appear in your logs.

    The runner does not expose a Teams webhook. Teams delivers to the
    Intelligence messaging endpoint, which setup registered on the bot for
    you.

  </Step>

  <Step>
    ### Configure secrets and start [#configure-secrets-and-start]

    ```dotenv title=".env"
    CPK_INTELLIGENCE_API_KEY=<project-api-key>
    CHANNEL_CODE=support-teams
    # Add the agent variables shown for your selected backend.
    PORT=3001

    # Optional paired overrides for self-hosted or non-production Intelligence:
    # INTELLIGENCE_API_URL=https://intelligence.example.com
    # INTELLIGENCE_GATEWAY_WS_URL=wss://realtime.intelligence.example.com
    ```

    The runner uses port `3001` so it can run alongside a web app
    on port `3000`. If `3001` is already in use, set `PORT` to another free port.

    #### Where these values come from [#where-these-values-come-from]

    Three variables matter here:

    - `OPENAI_API_KEY`, or the key for whichever model provider your agent uses.
      This one is yours to create and paste.
    - `CPK_INTELLIGENCE_API_KEY`: `npx copilotkit@latest project select` writes
      it to `.env` and provisions the project and its key.
    - `CHANNEL_CODE`: the Code shown on the Channel in Intelligence.

    If you started with the coding-agent prompt above, the onboarding run
    writes both Intelligence values for you. To set them yourself, see
    [configure the runtime handoff](/teams/intelligence#configure-the-runtime-handoff)
    for where each value appears in Intelligence.

    Cloud-hosted Intelligence supplies both default base URLs. For a
    self-hosted or non-production deployment, override both together. The REST
    and realtime planes use separate hosts, so do not derive the WebSocket URL
    from the API URL. Pass each as a bare base URL without `/api`, `/socket`,
    `/runner`, or `/client`. Create the project-scoped runtime key from **API
    Keys** in the Intelligence project sidebar.

    Start the selected agent backend, then run:

    ```bash title="Terminal"
    node --env-file=.env --import tsx channel.ts
    ```

    Intelligence should report **Online**.

    #### Know the healthy state [#know-the-healthy-state]

    | Status | What to check |
    | --- | --- |
    | **Disabled** | Enable the Channel before expecting delivery. |
    | **Setup incomplete** | Finish the selected provider's required setup fields before starting the runtime. |
    | **Setup failed** | Reopen platform setup and correct the rejected credentials or configuration. |
    | **Waiting for runtime** | Start the process, and match its Code and provider to this Channel. |
    | **Conflict** | Compare every replica's complete Channel declaration set. Identical replicas should elect one active owner and connected standbys; different but overlapping sets are unsafe. |
    | **Offline** | Check the runner process, network, and Intelligence gateway connection. |
    | **Delivery failing** | Check platform credentials, app permissions, and the provider response. |
    | **Online** | The runtime is connected; send a real provider message to verify the full path. |

  </Step>

  <Step>
    ### Verify a real Teams message [#verify-a-real-teams-message]

    Open the app in Teams, add it to a chat or team, then send:

    ```text title="Microsoft Teams"
    Summarize the decisions in this conversation.
    ```

    In a team channel, mention the bot. A message that does not mention it is
    ambient, and an ambient message only reaches your agent once a thread has
    been subscribed to.

    A real response validates the bot registration, Intelligence messaging
    endpoint, managed credentials, the runner, the agent, and the Adaptive Card
    reply path.

  </Step>
</Steps>

## Troubleshooting [#troubleshooting]

<Accordions>
  <Accordion title="The Channel stays at Waiting for runtime">
    Confirm the Code matches `CHANNEL_CODE` and the API key belongs to the same
    Intelligence project. Provider routing comes from the Teams connection
    attached in Intelligence, not from a `createChannel` option.
  </Accordion>
  <Accordion title="Teams cannot reach the bot">
    In Teams Developer Portal, open **Tools → Bot management**, select the bot,
    and compare its endpoint address with the messaging endpoint shown in
    Intelligence. They must match exactly, including no leading or trailing
    space. Developer Portal rejects a padded value and reports it as a save
    failure, which reads like a portal fault rather than a bad value. A bot with
    the wrong endpoint completes setup and then never receives anything.

    This is not your runner's `PORT`. The runner takes no inbound provider
    traffic at all.
  </Accordion>
  <Accordion title="The app package is rejected">
    Upload the complete zip that setup produced; do not unzip it and upload only
    `manifest.json`. If the app is already in the team and you are re-adding it
    to change permissions, remove it first, because Teams settles app permissions only
    while the app is being added.
  </Accordion>
  <Accordion title="Startup settles but does not become Online">
    Inspect `channels.status()` after the guard in the runner. Finish any
    **Setup incomplete** state in Intelligence. If Intelligence reports
    **Conflict**, compare the complete Channel declaration set on every replica;
    identical replicas should elect an active owner and standbys.
  </Accordion>
</Accordions>

## What kind of bot this is [#what-kind-of-bot-this-is]

This section is for the Microsoft 365 admin who approves the bot. You do not need it to run the Channel.

Microsoft supports more than one kind of bot identity. Setup creates a
**Teams-managed** bot: Teams Developer Portal owns the registration, and its app
ID and client secrets live there under **Tools → Bot management**, in your
directory, rotatable by your own admins. It is registered single-tenant, so it is
scoped to your organization. Nothing is created in your Azure account and nothing
is billable. If you stop using CopilotKit the registration stays in your
Developer Portal; removing it is yours to do.

The alternative Microsoft offers is an **Azure Bot**: a billable Azure Bot
Service resource in your own subscription, needing a subscription, resource
group, and region. Microsoft's Teams CLI recognizes only these two kinds; a
self-managed Microsoft Entra app registration that you create and manage yourself
is not something it can produce or consume.

Treat the choice as permanent. Microsoft provides a one-way `teams app bot
migrate` to Azure that replaces the existing registration, with nothing to
migrate back. CopilotKit itself is indifferent to which kind you point a Channel
at (Intelligence performs an ordinary client-credentials grant with the app ID,
tenant ID, and secret), but the app ID is embedded in the app package as the bot
ID, so changing identity means generating a fresh package, uploading it, and
re-installing.

Next, [map application users and choose Memory grants](/teams/identity-and-memory),
add [tools and context](/teams/tools), or build
[interactive approvals](/teams/interactive).
