0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FastMCP を 0.0.0.0 で Listen して外部からアクセスできるようにするまでの道のり

Posted at

はじめに

Model Context Protocol(略して MCP)フレームワークを使ってカスタムツールサーバーを書いていると、FastMCP クラスがすごく便利ですよね。
特に streamable-http をトランスポートに選んだとき、ローカルループバック(127.0.0.1)ではなく LAN やインターネットからアクセスできるように 0.0.0.0 で Listen したくなることがあります。

しかし、host="0.0.0.0" を指定しようとすると TypeError が出てしまう……。
本記事では、なぜこのエラーが起きるのかを FastMCP のソースコードまで読み解きながら説明し、正しい設定方法を紹介します。


よくある失敗パターン

1. run() に直接 host を渡す

from mcp.server.fastmcp import FastMCP
mcp = FastMCP("oci-compute")
mcp.run(transport="streamable-http", host="0.0.0.0")

実行すると……

TypeError: FastMCP.run() got an unexpected keyword argument 'host'

2. transport_options を使ってみる

mcp.run(
    transport="streamable-http",
    transport_options={"host": "0.0.0.0", "port": 8000}
)

ダメでした。

TypeError: FastMCP.run() got an unexpected keyword argument 'transport_options'

根本原因をソースコードで読み解く

1. run() のシグネチャ

mcp/server/fastmcp/server.py より抜粋:

def run(
    self,
    transport: Literal["stdio", "sse", "streamable-http"] = "stdio",
    mount_path: str | None = None,
) -> None:
    ...

→ 引数は transportmount_path のみ。hostport を受け付けていない。

2. __init__() のシグネチャ

class FastMCP(Generic[LifespanResultT]):
    def __init__(
        self,
        name: str | None = None,
        ...
        host: str = "127.0.0.1",
        port: int = 8000,
        ...
    ):
        self.settings = Settings(
            ...
            host=host,
            port=port,
            ...
        )

→ なるほど!host, port はインスタンス生成時にしか設定できない ようです。
run() の内部で Uvicorn を起動する際に、この settings 値を参照しています。


正しい設定方法

インスタンスを作る段階で host="0.0.0.0" を指定しましょう。

# oci-compute-mcp-server.py
from mcp.server.fastmcp import FastMCP

# ここで host/port を渡す
mcp = FastMCP("oci-compute", host="0.0.0.0", port=8000)

# ... 各種ツール定義 ...

if __name__ == "__main__":
    mcp.run(transport="streamable-http")

実行結果:

INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)

これで LAN やポートフォワーディング経由で外部からアクセスできるようになります!


まとめ

  • FastMCP の ネットワーク設定はコンストラクタで行う
  • run() はあくまでトランスポートを選ぶだけ。
  • API が「意図した通りに動かない」ときは、素直にソースを読むのが最短ルート。

Happy MCP Hacking!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?