1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MCPサーバー構築入門ならSDKのREADMEがおすすめ

Posted at

前回までのあらすじ

前回はなんだか微妙な終わり方をしたので、MCPサーバーを今日は確実に構築したい。
改めてBuilding MCP with LLMsに沿ってやってみたけど、ライブラリの依存関係やimportでループに陥るので、LLMに作ってもらうのは一旦諦める。

MCP公式の手動チュートリアルは以下

だけど、Python SDKのREADMEが一番シンプルでMCPの大枠を掴みやすかったのでお勧め。

↑のQuickstartに沿って実装し、MCP公式のInspector↓で動作確認する。

動作確認

Python SDKのREADMEよりQuickstartのコード:

# server.py
from mcp.server.fastmcp import FastMCP

# Create an MCP server
mcp = FastMCP("Demo")


# Add an addition tool
@mcp.tool()
def add(a: int, b: int) -> int:
   """Add two numbers"""
   return a + b


# Add a dynamic greeting resource
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
   """Get a personalized greeting"""
   return f"Hello, {name}!"

Resources

image.png

Inspectorで接続し、List ResourcesList Templatesをクリックした後の画面。

  • Resourcesタブが選択されている
  • Resourcesが空
  • Resource Templatesget_greetingがある

image.png
get_greetingを選択すると、nameを入力して機能を利用してみることができた。
image.png

Tools

image.png

Toolsタブに切り替えると、addが表示された。
image.png
こんな感じで機能も使えるようだ。

拡張してみる

Resourcesに表示させる

上のResourcesタブでResourcesリストが空だったので、ここに表示させるように拡張したい。

Python SDKのREADMEのResourcesセクションのコードを末尾に追加してみる。

@mcp.resource("config://app")
def get_config() -> str:
   """Static configuration data"""
   return "App configuration here"


@mcp.resource("users://{user_id}/profile")
def get_user_profile(user_id: str) -> str:
   """Dynamic user data"""
   return f"Profile data for user {user_id}"

image.png

Resources欄にconfig://appが、Resource Templates欄にget_user_profileが追加された。
引数を取るResourceがResource Templatesに分類される模様。

Promptを追加する

Python SDKのREADMEのPromptsセクションのコードを末尾に追加した。

@mcp.prompt()
def review_code(code: str) -> str:
   return f"Please review this code:\n\n{code}"


@mcp.prompt()
def debug_error(error: str) -> list[base.Message]:
   return [
       base.UserMessage("I'm seeing this error:"),
       base.UserMessage(error),
       base.AssistantMessage("I'll help debug that. What have you tried so far?"),
   ]

image.png
Promptsタブにreview_codedebug_errorが表示され、それぞれ引数を入力してプロンプトを作成することができた。

まとめ

MCPに関しては、正直情報量の多さに追いつけなかったので、やるべきことをできるだけシンプルにすることを目指した。結果としてMCP機能の全体像を俯瞰することができた。今後はクライアントでMCPサーバーを実際に使用してみたい。

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?