Web コンテンツをホストし、エージェントの HTTP サーバーを管理する

Teams SDK エージェントは HTTP サーバーです。 既定では、SDK は自動的にそのサーバーを作成し、 /api/messages エンドポイントを登録して、そのライフサイクルを管理します。 さらに進んで同じサーバーを使用して Web コンテンツをホストすることも、サーバー全体を引き継ぐこともできます。

静的 Web コンテンツをホストする

App クラスは、エージェントと共に Web アプリをホストできます。 これにより、エージェントとタブ アプリの両方を 1 つの手順で構築、展開、サイドロードできるため、効率的な内部ループが得られます。 また、エージェント設定ページやダイアログなどの単純なエクスペリエンスにも、運用環境で役立ちます。

index.html ファイルを含むフォルダーをホストするには、TypeScript と Python では SDK のタブ ヘルパーを使用するか、C# では静的ファイルのミドルウェア ASP.NET Core使用します。

SDK 2.1 では、ASP.NET Core 静的ファイル ミドルウェアを使用して、タブ ルートの下の Web ビルド ディレクトリからファイルを提供します。

using Microsoft.Extensions.FileProviders;

string tabDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Web", "bin");
app.UseStaticFiles(new StaticFileOptions
{
  FileProvider = new PhysicalFileProvider(tabDirectory),
  RequestPath = "/tabs/myApp"
});

app.MapGet("/tabs/myApp", () =>
{
  return Results.File(Path.Combine(tabDirectory, "index.html"), "text/html");
});

サーバーを起動する前に、 Web/bin ディレクトリとその index.html を作成します。 静的ファイルのミドルウェアは、そのディレクトリ内のファイルのみを提供します。信頼されていない URL セグメントから直接ファイル パスを作成しないでください。 ルートは、ローカル開発中は http://localhost:PORT/tabs/myApp でホストされ、デプロイ後は https://BOT_DOMAIN/tabs/myApp でホストされます。

import path from 'path';

app.tab('myApp', path.resolve('dist/client'));

これにより、ローカル開発中は http://localhost:PORT/tabs/myApp でホストされ、デプロイされると https://BOT_DOMAIN/tabs/myApp でホストされるルートが登録されます。

import os

app.tab("my_app", os.path.abspath("dist/client"))

これにより、ローカル開発中は http://localhost:PORT/tabs/my_app でホストされ、デプロイされると https://BOT_DOMAIN/tabs/my_app でホストされるルートが登録されます。

ホスト ドメインをアプリ マニフェストの validDomains 配列に追加し、他の場所でホストされているタブの場合と同じように、タブ定義からルートを参照します。 詳細については、「 Teams のタブを作成する」を参照してください。

HTTP サーバーを自分で管理する

TypeScript と Python では、 app.start() を呼び出すと HTTP サーバーが起動し、そのライフサイクルが管理されます。 C# では、ASP.NET Core がサーバーを所有し、webApp.Run() を呼び出します。 次のときは、サーバーを自分で制御します。

  • 既に独自のサーバーとルートを持つアプリに Teams サポートを追加します。
  • TLS、ワーカー プロセス、フレームワーク ミドルウェアなどのサーバー構成を制御します。
  • SDK の組み込みの既定値以外の HTTP フレームワークを使用します。

TypeScript と Python では、カスタム HTTP サーバー アダプターがサポートされています。C# では ASP.NET Core を直接使用します。

メカニズム

TypeScript と Python では、SDK は HTTP 処理を 2 つのレイヤーに分割します。

  • HTTP サーバーは、JSON Web トークン (JWT) 認証、アクティビティの解析、ハンドラーへのルーティングといった Teams プロトコルの問題を処理します。
  • HTTP サーバー アダプターは、フレームワークに関する問題 (HTTP フレームワークの要求と応答モデルと SDK のハンドラー パターン間の変換) を処理します。

Teams からの受信要求はアダプターを通過して、認証と解析のために HTTP サーバーに入り、次にハンドラーに渡されます。 応答は同じ経路をたどって戻ります。

SDK は ASP.NET Core によってホストされるため、既に WebApplication とそのライフサイクルを所有しています。 依存関係の挿入にエージェントを登録し、そのエンドポイントを独自の WebApplicationにマップして、アプリを自分で実行します。

SDK では、組み込みの HTTP フレームワークとして Express を使用します。 アダプター インターフェイスが小さい:

interface IHttpServerAdapter {
  registerRoute(method: HttpMethod, path: string, handler: HttpRouteHandler): void;
  serveStatic?(path: string, directory: string): void;
  start?(port: number): Promise<void>;
  stop?(): Promise<void>;
}

type HttpRouteHandler = (request: { body: unknown; headers: Record<string, string | string[]> })
  => Promise<{ status: number; body?: unknown }>;

SDK は、組み込みの HTTP フレームワークとして FastAPI を使用します。 アダプター インターフェイスが小さい:

class HttpServerAdapter(Protocol):
    def register_route(self, method: HttpMethod, path: str, handler: HttpRouteHandler) -> None: ...
    def serve_static(self, path: str, directory: str) -> None: ...
    async def start(self, port: int) -> None: ...
    async def stop(self) -> None: ...

class HttpRouteHandler(Protocol):
    async def __call__(self, request: HttpRequest) -> HttpResponse: ...

TypeScript または Python カスタム アダプターの場合、ルート登録のみが必要です。

  • レジスタ ルート が必要です。 SDK は、 /api/messages や /api/functions/{name} などのルートを動的に登録します。
  • 静的を提供する は省略可能です。 タブまたは静的ページを提供する場合にのみ必要です。
  • 開始 と 停止 は省略可能です。 サーバー ライフサイクルを自分で管理する場合は省略します。

既存のサーバーに Teams を追加する

既に所有しているサーバーに Teams を追加するには:

  1. 独自のルートとミドルウェアを使用してサーバーを作成します。
  2. アダプターでラップします。
  3. TypeScript または Python で、アプリの initialize() メソッドを呼び出して、Teams ルートを登録します。 C# の場合、ASP.NET Core アプリ上の Teams を UseTeamsBotApplication() に登録します。
  4. サーバーを自分で起動します。
using Microsoft.Teams.Apps;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// 1. Register the agent alongside your own services.
builder.Services.AddTeamsBotApplication();

WebApplication webApp = builder.Build();

// 2. Map the Teams endpoints onto your own WebApplication.
TeamsBotApplication teams = webApp.UseTeamsBotApplication();

teams.OnMessage(async (context, cancellationToken) =>
{
  await context.SendAsync($"Echo: {context.Activity.Text}", cancellationToken);
});

// 3. Add your own routes and middleware.
webApp.MapGet("/health", () => Results.Json(new { status = "healthy" }));

// 4. Run the server yourself.
webApp.Run();
import express from 'express';
import http from 'http';
import { App, ExpressAdapter } from '@microsoft/teams.apps';

// 1. Create your Express app with your own routes.
const expressApp = express();
const httpServer = http.createServer(expressApp);

expressApp.get('/health', (_req, res) => {
  res.json({ status: 'healthy' });
});

// 2. Wrap it in the ExpressAdapter.
const adapter = new ExpressAdapter(httpServer);

// 3. Create the Teams app with the adapter.
const app = new App({ httpServerAdapter: adapter });

app.on('message', async ({ send, activity }) => {
  await send(`Echo: ${activity.text}`);
});

// 4. Initialize. This registers /api/messages on your Express app, but doesn't start a server.
await app.initialize();

// 5. Start the server yourself.
httpServer.listen(3978, () => console.log('Server ready on http://localhost:3978'));

注:

app.initialize() 各プラグインの onInit フックを実行しますが、 onStart フックは実行しません。 onStart app.start()からのみ発生します。 onStart でセットアップを行うプラグインを使用する場合は、app.start() を呼び出してサーバーを管理させるか、app.initialize()後にそのプラグインのonStartを自分で呼び出します。

await app.initialize();
await myPlugin.onStart({ port: 3978 });
import asyncio

import uvicorn
from fastapi import FastAPI
from microsoft_teams.apps import App, FastAPIAdapter

# 1. Create your FastAPI app with your own routes.
my_fastapi = FastAPI(title="My App + Teams agent")

@my_fastapi.get("/health")
async def health():
    return {"status": "healthy"}

# 2. Wrap it in the FastAPIAdapter.
adapter = FastAPIAdapter(app=my_fastapi)

# 3. Create the Teams app with the adapter.
app = App(http_server_adapter=adapter)

@app.on_message
async def handle_message(ctx):
    await ctx.send(f"Echo: {ctx.activity.text}")

async def main():
    # 4. Initialize. This registers /api/messages on your FastAPI app, but doesn't start a server.
    await app.initialize()

    # 5. Start the server yourself.
    config = uvicorn.Config(app=my_fastapi, host="0.0.0.0", port=3978)
    server = uvicorn.Server(config)
    await server.serve()

asyncio.run(main())

別のフレームワークを使用する

C# SDK は ASP.NET Core によってホストされ、プラグ可能な HTTP フレームワーク アダプターは提供されません。 別のスタックでエージェントをホストするには、その前に ASP.NET Core アプリを配置するか、登録UseTeamsBotApplication()/api/messagesエンドポイントに要求を転送します。

組み込みの既定値以外のフレームワークを使用するには、そのフレームワークのアダプター インターフェイスを実装します。 ほとんどの作業はルート登録で行われます。受信要求を本文とヘッダーのペアに変換し、ハンドラーを呼び出して、応答を書き戻します。

サーバーのライフサイクルはユーザーが自分で管理するため、start メソッドと stop メソッドは必要ありません。 タブまたは静的ページを提供する場合にのみ、serve static メソッドを実装します。

次の Restify アダプターは、ルート登録のみを実装します。

import assert from 'node:assert/strict';
import restify from 'restify';
import { HttpMethod, IHttpServerAdapter, HttpRouteHandler } from '@microsoft/teams.apps';

class RestifyAdapter implements IHttpServerAdapter {
  constructor(private server: restify.Server) {
    this.server.use(restify.plugins.bodyParser());
  }

  registerRoute(method: HttpMethod, path: string, handler: HttpRouteHandler): void {
    // Teams sends only POST requests to your agent endpoint.
    assert(method === 'POST', `Unsupported method: ${method}`);
    this.server.post(path, async (req: restify.Request, res: restify.Response) => {
      const response = await handler({
        body: req.body,
        headers: req.headers as Record<string, string | string[]>,
      });
      res.send(response.status, response.body);
    });
  }
}

使用方法:

const server = restify.createServer();
const adapter = new RestifyAdapter(server);
const app = new App({ httpServerAdapter: adapter });
await app.initialize();
server.listen(3978);

組み込みの既定値以外のフレームワークを使用するには、そのフレームワークのアダプター プロトコルを実装します。 ほとんどの作業は register_route で行います。受信要求を HttpRequest に変換し、ハンドラーを呼び出して、 HttpResponse を書き戻します。

サーバーのライフサイクルを自分で管理するため、 start や stopは必要ありません。 serve_static は、タブまたは静的ページを提供する場合にのみ実装してください。

次の Starlette アダプターは、 register_routeのみを実装します。

from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.routing import Route
from microsoft_teams.apps.http.adapter import HttpMethod, HttpRequest, HttpResponse, HttpRouteHandler

class StarletteAdapter:
    def __init__(self, app: Starlette):
        self._app = app

    def register_route(self, method: HttpMethod, path: str, handler: HttpRouteHandler) -> None:
        # Teams sends only POST requests to your agent endpoint.
        async def starlette_handler(request: Request) -> Response:
            body = await request.json()
            headers = dict(request.headers)
            result: HttpResponse = await handler(HttpRequest(body=body, headers=headers))
            if result.get("body") is not None:
                return JSONResponse(content=result["body"], status_code=result["status"])
            return Response(status_code=result["status"])

        route = Route(path, starlette_handler, methods=[method])
        self._app.routes.insert(0, route)

使用方法:

starlette_app = Starlette()
adapter = StarletteAdapter(starlette_app)
app = App(http_server_adapter=adapter)
await app.initialize()
# Start Starlette with uvicorn yourself.

関連項目