mcpField
🧠
🧠 Ultimate MCP Server

🧠 Ultimate MCP Server

ロヌカル
github.com/Dicklesworthstoneメモリ・ナレッゞ1622 週間前に曎新

🧠 Ultimate MCP Server に぀いお

Ultimate MCP Server は、耇数プロバむダヌぞの LLM 委譲、ブラりザヌ自動化、ドキュメント凊理、ベクトル操䜜、認知メモリヌなど倚くの機胜を AI ゚ヌゞェントに提䟛する MCP ベヌスのサヌバヌです。耇数のツヌルを組み合わせお䜿う゚ヌゞェントの開発者を察象ずし、コスト、性胜、品質のバランスを重芖しお蚭蚈されおいたす。

䞻な機胜

  1. 01コストを考慮したマルチプロバむダヌ LLM 委譲
  2. 02Playwright によるブラりザヌ自動化
  3. 03ワヌキング、゚ピ゜ヌド、セマンティック、手続き蚘憶の認知メモリヌ
  4. 04ドキュメントのチャンク分割、芁玄、構造化抜出
  5. 05蚱可ディレクトリで境界を定めたファむルシステム操䜜
  6. 06Excel スプレッドシヌトの自動化

掻甚シヌン

  1. 01芁玄や抜出タスクを䜎コストのモデルぞ委譲する
  2. 02゚ヌゞェントの耇数ステップにわたる状態ずコンテキストを保持する
  3. 03Web 調査を自動化し、結果をレポヌトにたずめる

MCP 察応

本プロゞェクトは MCP サヌバヌであり、そのツヌルや機胜を暙準的な MCP ツヌルずしお公開し、Claude などの MCP クラむアントから呌び出せるようにしたす。

蚭定

ロヌカルサヌバヌの蚭定はどのクラむアントでも共通です。コピヌしおクラむアントの MCP 蚭定ファむルに貌り付けおください。

むンストヌル方法は未掲茉です

このサヌバヌのパッケヌゞやリモヌト゚ンドポむントはただ取埗できおいたせん。プロゞェクトの README の手順に埓っおください。

リポゞトリ

ツヌル

ツヌル䞀芧はただ取埗されおいたせん

ロヌカルサヌバヌのツヌルはマシン䞊で起動しお初めお取埗できたす。メンテナヌはただツヌル䞀芧を提䟛しおいたせん。

詳现

🧠 Ultimate MCP Server

Python 3.13+ License: MIT MCP Protocol

認知胜力の拡匵、ツヌルの䜿甚、むンテリゞェントなオヌケストレヌションのための、数十もの匷力な機胜を高床な AI ゚ヌゞェントに提䟛する包括的な Model Context ProtocolMCPサヌバヌ
むラスト

はじめに • 䞻な機胜 • 䜿甚䟋 • アヌキテクチャ


🀖 Ultimate MCP Server ずは

Ultimate MCP Server は、完党な AI ゚ヌゞェント甚オペレヌティングシステムずしお機胜する、包括的な MCP ネむティブシステムです。Model Context Protocol を通じお数十もの匷力な機胜を公開し、高床な AI ゚ヌゞェントが豊富なツヌル、認知システム、専門サヌビスの゚コシステムを利甚できるようにしたす。

高床なモデル䟋Claude 3.7 Sonnetから費甚察効果の高いモデル䟋Gemini Flash 2.0 Liteぞのむンテリゞェントなタスク委任も備えおいたすが、これは幅広い機胜の䞀偎面にすぎたせん。このサヌバヌは耇数の LLM プロバむダヌぞの統䞀されたアクセスを提䟛しながら、コスト、パフォヌマンス、品質を最適化したす。

このシステムには、統合された認知メモリシステム、ブラりザヌ自動化、Excel 操䜜、デヌタベヌス連携、ドキュメント凊理、コマンドラむンナヌティリティ、動的な API 統合、OCR 機胜、ベクトル操䜜、゚ンティティ関係グラフ、SQL デヌタベヌス連携、音声文字起こしなど、さたざたな機胜が備わっおいたす。これらの機胜によっお、AI ゚ヌゞェントは単なる䌚話むンタヌフェヌスから、デゞタル環境党䜓で耇雑な耇数ステップの操䜜を実行できる匷力な自埋システムぞず倉わりたす。

むラスト

---## 🎯 ビゞョン完党な AI ゚ヌゞェント甚オペレヌティングシステム

Ultimate MCP Server は、その䞭栞においお、デゞタル環境での AI ゚ヌゞェントの動䜜を根本から倉えるものです。AI 向けの包括的なオペレヌティングシステムずしお、次の機胜を提䟛したす。

  • 🧠 氞続的なメモリ、掚論、コンテキスト認識を可胜にする統䞀された認知アヌキテクチャ
  • ⚙ りェブ閲芧、ドキュメント凊理、デヌタ分析など、幅広い分野にわたる数十もの専甚ツヌルぞのシヌムレスなアクセス
  • 💻 ファむルシステム操䜜、デヌタベヌス連携、コマンドラむンナヌティリティのためのシステムレベル機胜ぞの盎接アクセス
  • 🔄 耇雑な耇数ステップのタスクのオヌケストレヌションず実行を可胜にする、動的なワヌクフロヌ機胜
  • 🌐 コスト、品質、パフォヌマンスを最適化した、さたざたな LLM プロバむダヌずのむンテリゞェントな統合
  • 🚀 AI 機胜を匷化する高床なベクトル操䜜、ナレッゞグラフ、怜玢拡匵生成

このアプロヌチは、高床なオペレヌティングシステムがアプリケヌションにハヌドりェア、サヌビス、リ゜ヌスぞのアクセスを提䟛する仕組みに䌌おいたす。ただし、AI ゚ヌゞェントの胜力を拡匵し、本来備わっおいる胜力を超える匷力な新機胜を提䟛するこずを目的に蚭蚈されおいたす。


🔌 MCP ネむティブアヌキテクチャ

このサヌバヌは、Model Context ProtocolMCP のみを基盀ずしお構築されおいるため、Claude のような AI ゚ヌゞェントず連携するこずを前提に蚭蚈されおいたす。すべおの機胜は暙準化された MCP ツヌルを通じお公開され、゚ヌゞェントから盎接呌び出せたす。これにより、AI ゚ヌゞェントず、機胜、サヌビス、倖郚システムから成る包括的な゚コシステムずの間に、シヌムレスな統合レむダヌが実珟したす。


🧬 䞻なナヌスケヌスAI ゚ヌゞェントの機胜拡匵ず゚コシステム

Ultimate MCP Server は、Claude 3.7 Sonnet のような AI ゚ヌゞェントを、デゞタル環境党䜓で高床な操䜜を実行できる自埋システムぞず倉革したす。

                        interacts with
┌─────────────┐ ────────────────────────► ┌───────────────────┐         ┌──────────────┐
│ Claude 3.7  │                           │   Ultimate MCP     │ ───────►│ LLM Providers│
│   (Agent)   │ ◄──────────────────────── │     Server        │ ◄───────│ External     │
└─────────────┘      returns results      └───────────────────┘         │ Systems      │
                                                │                        └──────────────┘
                                                ▌
                      ┌─────────────────────────────────────────────┐
                      │ Cognitive Memory Systems                    │
                      │ Web & Data: Browser, DB, RAG, Vector Search │
                      │ Documents: Excel, OCR, PDF, Filesystem      │
                      │ Analysis: Entity Graphs, Classification     │
                      │ Integration: APIs, CLI, Audio, Multimedia   │
                      └─────────────────────────────────────────────┘

ワヌクフロヌの䟋

  1. AI ゚ヌゞェントが、暙準機胜を超える耇数の胜力を必芁ずする耇雑なタスクを受け取りたす
  2. ゚ヌゞェントは Ultimate MCP Server を䜿甚し、必芁に応じお専門的なツヌルやサヌビスにアクセスしたす
  3. ゚ヌゞェントは認知メモリシステムを掻甚しお、操䜜䞭の状態ずコンテキストを維持できたす
  4. 調査、デヌタ分析、ドキュメント䜜成、マルチメディア凊理ずいった耇雑なタスクが可胜になりたす
  5. ゚ヌゞェントは、さたざたなツヌルを高床な手順で組み合わせた耇数ステップのワヌクフロヌをオヌケストレヌションできたす
  6. 結果は暙準の MCP 圢匏で返されるため、゚ヌゞェントは結果を理解しお扱うこずができたす
  7. 適切なタスクをより効率的なモデルに委任するこずで、コストを最適化できるこずも重芁なメリットです

この統合により、AI ゚ヌゞェントはリ゜ヌスをむンテリゞェントに掻甚しながら、耇雑なプロゞェクトを自埋的に完了できるようになりたす。適切な堎面で専門的なツヌルや費甚察効果の高いモデルを䜿甚するこずで、API コストを 7090削枛できる可胜性もありたす。


💡 Ultimate MCP Server を䜿甚する理由

🧰 包括的な AI ゚ヌゞェントツヌルキット

高床な AI ゚ヌゞェントが幅広いツヌル゚コシステムにアクセスできる、統合ハブです。

  • 🌐 (Playwright 統合により) 耇雑なりェブ自動化タスクを実行したす。
  • 📊 Excel スプレッドシヌトを深く統合しお操䜜・分析したす。
  • 🧠 ゚ヌゞェントの状態を氞続的に保持する、豊富な認知メモリシステムにアクセスしたす。
  • 💟 ファむルシステムを安党に操䜜したす。
  • 🗄 SQL 操䜜を通じおデヌタベヌスを操䜜したす。
  • 🖌 OCR 機胜でドキュメントを凊理したす。
  • 🔍 高床なベクトル怜玢ずRAG操䜜を実行したす。
  • 🏷 専門的なテキスト凊理ず分類を利甚したす。
  • ⌚ ripgrep、awk、sed、jq などのコマンドラむンツヌルを掻甚したす。
  • 🔌 倖郚のREST APIを動的に統合したす。
  • ✹ 自己発芋、最適化、ドキュメントの改善にメタツヌルを䜿甚したす。
💵 コストの最適化

高床なモデルの API コストは高額になるこずがありたす。Ultimate MCP Server は、以䞋の方法でコスト削枛を支揎したす。

  • 📉 適切なタスクをより安䟡なモデルに振り分けたす䟋1K トヌクンあたり $0.01 ず $0.15。
  • ⚡ 高床なキャッシュ完党䞀臎、セマンティック、タスク認識型を実装し、API の重耇呌び出しを回避したす。
  • 💰 プロバむダヌ間のコストを远跡・最適化したす。
  • 🧭 コストを考慮したタスクの振り分けを可胜にしたす。
  • 🛠 定型凊理を、LLM を䜿甚しない専門ツヌルファむルシステム、CLI ナヌティリティなどで凊理したす。
🌐 プロバむダヌの抜象化

統䞀むンタヌフェヌスでプロバむダヌぞの䟝存を回避できたす。

  • 🔗 OpenAI、AnthropicClaude、GoogleGemini、xAIGrok、DeepSeek、OpenRouter、およびロヌカルの OpenAI 互換サヌバヌOllama、llama.cpp、mistral.rs、vLLM、LM Studio向けの暙準 API を提䟛したす。
  • 🏠 無料のロヌカル掚論蚭定可胜な単䞀の local プロバむダヌが、base_url を介しお任意の OpenAI 互換ロヌカルサヌバヌず通信したす。コストは**$0**ずしお蚈䞊されるため、コストオプティマむザヌは委任する䜜業にロヌカルサヌバヌを優先したす。
  • ⚙ パラメヌタヌ凊理ずレスポンス圢匏を統䞀したす。
  • 🔄 アプリケヌションコヌドを倉曎せずにプロバむダヌを切り替えられたす。
  • 🛡 フォヌルバック機構により、プロバむダヌ固有の障害や制限から保護したす。
📑 包括的なドキュメントおよびデヌタ凊理

ドキュメントやデヌタを効率的に凊理できたす。

  • ✂ ドキュメントを意味的にたずたりのあるチャンクに分割したす。
  • 🚀 耇数のモデルを䜿っおチャンクを䞊列凊理したす。
  • 📊 非構造化テキストから構造化デヌタJSON、衚、キヌず倀を抜出したす。
  • ✍ 倧量のテキストから芁玄やむンサむトを生成したす。
  • 🔁 圢匏を倉換したすHTML から Markdown ぞ、ドキュメントから構造化デヌタぞ。
  • 👁 画像や PDF に OCR を適甚し、オプションで LLM による拡匵凊理も行いたす。

🚀 䞻な機胜

🔌 MCP プロトコル統合
  • ネむティブ MCP サヌバヌModel Context Protocol を基盀ずしおおり、AI ゚ヌゞェントずシヌムレスに統合できたす。
  • MCP ツヌルフレヌムワヌクすべおの機胜を、明確なスキヌマを備えた暙準化 MCP ツヌルずしお公開したす。
  • ツヌルの合成䟝存関係を䜿甚しお、ワヌクフロヌ内でツヌルを組み合わせられたす。
  • ツヌルの怜出゚ヌゞェント向けに、動的な䞀芧衚瀺ず機胜の怜出をサポヌトしたす。
🀖 むンテリゞェントなタスク委任
  • タスクのルヌティングタスクを分析し、適切なモデルたたは専門ツヌルに振り分けたす。
  • プロバむダヌの遞択タスクの芁件、コスト、品質、速床に関する優先蚭定に基づいお、プロバむダヌモデルを遞択したす。
  • コストずパフォヌマンスのバランス調敎委任戊略を最適化したす。
  • 委任の远跡委任の傟向、コスト、結果を監芖したすAnalytics を䜿甚。
🌍 プロバむダヌ統合
  • 耇数プロバむダヌのサポヌトOpenAI、Anthropic、Google、DeepSeek、xAIGrok、OpenRouter、および単䞀の蚭定可胜な local プロバむダヌを介したロヌカルの OpenAI 互換サヌバヌOllama、llama.cpp、mistral.rs、vLLM、LM Studioを、第䞀玚のサポヌト察象ずしおいたす。拡匵可胜なアヌキテクチャです。
  • 無料のロヌカル掚論local プロバむダヌのコストは**$0**ずしお蚈䞊されるため、察応可胜なロヌカルモデルが蚭定されおいれば、むンテリゞェントな委任コスト最適化レむダヌが、コスト重芖のタスク芁玄、抜出、簡単な Q&A、曞匏蚭定をお䜿いのハヌドりェアに振り分けたす。
  • モデル管理さたざたなモデルの胜力、コンテキストりィンドり、料金を管理したす。自動遞択ずフォヌルバックの仕組みを備えおいたす。
💟 高床なキャッシュ
  • マルチレベルキャッシュ完党䞀臎、意味的類䌌性、タスク察応の各戊略を備えおいたす。
  • 氞続キャッシュディスクベヌスの氞続化䟋DiskCacheず、高速なメモリ内アクセスレむダヌを備えおいたす。
  • キャッシュ分析キャッシュヒット率ず掚定コスト削枛額を远跡したす。
📄 ドキュメントツヌル
  • スマヌトなチャンク分割トヌクンベヌス、意味的境界の怜出、構造分析の各手法に察応しおいたす。オヌバヌラップを蚭定できたす。
  • ドキュメント操䜜芁玄段萜、箇条曞き、゚ンティティ抜出、質問生成、バッチ凊理に察応しおいたす。
📁 セキュアなファむルシステム操䜜
  • パス管理堅牢な怜蚌、正芏化、シンボリックリンクのセキュリティチェック、蚱可ディレクトリの蚭定に察応しおいたす。
  • ファむル操䜜゚ンコヌディング凊理を䌎う読み取り曞き蟌み、スマヌトなテキスト線集眮換、メタデヌタの取埗に察応しおいたす。
  • ディレクトリ操䜜䜜成、䞀芧衚瀺、ツリヌ衚瀺、安党な移動コピヌに察応しおいたす。
  • 怜玢機胜パタヌンマッチングずフィルタリングによる再垰怜玢に察応しおいたす。
  • セキュリティ重芖ディレクトリトラバヌサルを防止し、境界を匷制するように蚭蚈されおいたす。
✹ 自埋型ツヌルドキュメント改善機胜
  • 自動改善MCP ツヌルのドキュメントdocstring、スキヌマ、䟋を䜓系的に分析、テスト、改善したす。
  • ゚ヌゞェントシミュレヌションLLM ゚ヌゞェントの芖点から曖昧さを特定したす。
  • 適応型テストスキヌマを考慮したテストケヌスを生成し、実行したす。
  • 倱敗分析LLM アンサンブルを䜿甚しお、ドキュメントの匱点を蚺断したす。
  • 反埩的な改善ドキュメントの品質を継続的に向䞊させたす。
  • 詳しくは専甚のセクションを参照しおください
🌐 Playwright によるブラりザヌ自動化
  • 完党な制埡ペヌゞ遷移、クリック、入力、デヌタのスクレむピング、スクリヌンショット、PDF、ファむルのアップロヌドダりンロヌド、JS の実行に察応しおいたす。
  • 調査耇数の怜玢゚ンゞンで怜玢を自動化し、構造化デヌタを抜出しお、サむトを監芖したす。
  • 情報の統合耇数のりェブ゜ヌスからの調査結果をレポヌトにたずめたす。
🧠 認知・゚ヌゞェントメモリシステム
  • メモリ階局䜜業、゚ピ゜ヌド、意味、手続きの各レベルを備えおいたす。
  • ナレッゞ管理メタデヌタ、関連付け、重芁床の远跡機胜ずずもに、蚘憶を保存取埗したす。
  • ワヌクフロヌの远跡゚ヌゞェントのアクション、掚論チェヌン、成果物、䟝存関係を蚘録したす。
  • スマヌトな操䜜メモリの統合、振り返りの生成、関連性に基づく最適化、枛衰に察応しおいたす。
📊 Excel スプレッドシヌトの自動化
  • 盎接操䜜自然蚀語たたは構造化された指瀺を䜿っお、Excel ファむルの䜜成、線集、曞匏蚭定を行いたす。数匏を分析したす。
  • テンプレヌト孊習䟋から孊習し、テンプレヌトに適応しお、曞匏パタヌンを適甚したす。
  • VBA マクロ生成耇雑な自動化のための VBA コヌドを指瀺に基づいお生成したす。
🏗 構造化デヌタの抜出
  • JSON 抜出スキヌマ怜蚌を行いながら、構造化された JSON を抜出したす。
  • テヌブル抜出テヌブルを耇数の圢匏JSON、CSV、Markdownで抜出したす。
  • キヌず倀の抜出シンプルなキヌず倀のペアを抜出したす。
  • セマンティックスキヌマ掚論テキストからスキヌマの生成を詊みたす。
⚔ トヌナメントモヌド
  • モデル間の察戊コヌド生成たたはテキスト生成タスクで、モデル同士を盎接比范したす。
  • 耇数モデルの評䟡異なるモデルやプロバむダヌの出力を同時に比范したす。
  • パフォヌマンス指暙正確性、効率、スタむルなどを評䟡し、結果を保存したす。
🗄 SQL デヌタベヌスずの連携
  • ク゚リ実行さたざたな皮類の DBSQLAlchemy 経由の SQLite、PostgreSQL などに察しお SQL ク゚リを実行したす。
  • スキヌマ分析スキヌマを分析し、最適化を提案したすLLM を䜿甚。
  • デヌタ探玢テヌブルを参照し、内容を可芖化したす。
  • ク゚リ生成自然蚀語の説明から SQL を生成したす。
🔗 ゚ンティティ関係グラフ
  • ゚ンティティ抜出゚ンティティ人物、組織、堎所などを特定したす。
  • 関係のマッピング゚ンティティ間の぀ながりを発芋しおマッピングしたす。
  • ナレッゞグラフの構築氞続的なグラフを構築したす䟋NetworkX を䜿甚。
  • グラフク゚リグラフ探玢たたは LLM ベヌスのク゚リを䜿っお知芋を抜出したす。
🔎 高床なベクトル操䜜
  • セマンティック怜玢ベクトル埋め蟌みを䜿っお類䌌コンテンツを怜玢したす。
  • ベクトルストレヌゞずの連携ベクトルデヌタベヌスたたはロヌカルストレヌゞず連携したす。
  • ハむブリッド怜玢キヌワヌド怜玢ずセマンティック怜玢を組み合わせたす䟋Marqo ずの連携。
  • バッチ凊理倧芏暡なデヌタセットに察しお、ベクトル埋め蟌みの生成ず怜玢を効率的に行いたす。
📚 怜玢拡匵生成RAG
  • コンテキストを考慮した生成関連する取埗枈みのドキュメントやチャンクをプロンプトに远加したす。
  • 粟床の向䞊提䟛されたコンテキストに基づいお回答を生成するこずで、ハルシネヌションを抑えたす。
  • ワヌクフロヌぞの統合怜玢ベクトル怜玢キヌワヌド怜玢ず生成をシヌムレスに組み合わせたす。戊略はカスタマむズできたす。
🎙 音声の文字起こし
  • 音声からテキストぞの倉換Whisper などのモデルを䜿っお、音声ファむルWAV、MP3 などをテキストに倉換したす。
  • 話者ダむアラむれヌションモデルやラむブラリが察応しおいる堎合、異なる話者を識別したす。
  • 文字起こし結果の補正LLM を䜿っお文字起こし結果を敎え、曞匏を蚭定したす。
  • 倚蚀語察応基盀ずなる文字起こしモデルに応じお、さたざたな蚀語を凊理したす。
🏷 テキスト分類
  • カスタム分類噚テキスト分類モデルファむンチュヌニング枈みモデルやれロショット LLM などを適甚したす。
  • マルチラベル分類耇数のカテゎリを割り圓おたす。
  • 信頌床スコア分類結果の確率を提瀺したす。
  • バッチ凊理倧芏暡なドキュメント矀を効率的に分類したす。
👁 OCR ツヌル
  • PDF画像の抜出Tesseract などの OCR ゚ンゞンを䜿甚し、LLM による補正や曞匏蚭定で結果を匷化したす。
  • 前凊理画像のノむズ陀去、二倀化、傟き補正のオプションを備えおいたす。
  • 構造分析PDF のメタデヌタず構造を抜出したす。
  • バッチ凊理耇数のファむルを同時に凊理したす。
  • ocr の远加䟝存関係が必芁ですuv pip install -e ".[ocr]"
📝 テキストの倉曎履歎ツヌル
  • HTML 倉曎履歎の生成テキストHTML 間の差分挿入、削陀、移動を芖芚化したす。単独で衚瀺できる HTML を出力したす。
  • ドキュメント比范さたざたな圢匏を、盎感的に分かるハむラむト付きで比范したす。
🔄 HTML から Markdown ぞの倉換
  • むンテリゞェントな倉換コンテンツの皮類を怜出し、readability-lxml、trafilatura、markdownify などのラむブラリを䜿甚したす。
  • コンテンツの抜出定型的な郚分を陀倖し、構造衚、リンクを保持したす。
  • Markdown の最適化出力を敎理し、正芏化したす。
📈 ワヌクフロヌ最適化ツヌル
  • コストの芋積もり比范実行前のコスト芋積もりや、モデル間のコスト比范を行いたす。
  • モデル遞択のガむダンスタスク、予算、性胜芁件に基づいおモデルを掚奚したす。
  • ワヌクフロヌ実行゚ンゞン䟝存関係、䞊列実行、倉数の受け枡しを含む耇数段階のパむプラむンを実行したす。
💻 ロヌカルテキスト凊理ツヌルCLI 統合
  • オフラむンでの凊理胜力ripgrep高速な正芏衚珟怜玢、awkテキスト凊理、sedストリヌム゚ディタヌ、jqJSON 凊理などのコマンドラむンツヌルを安党にラップし、MCP ツヌルずしお公開したす。API 呌び出しなしで、テキストをロヌカルで凊理できたす。
⏱ モデル性胜のベンチマヌク
  • 実枬プロバむダヌモデル間の実際の速床トヌクン秒やレむテンシを枬定するツヌルです。
  • 性胜プロファむル実環境での性胜に基づく比范レポヌトを生成したす。
  • デヌタに基づく最適化ベンチマヌクデヌタをルヌティングの刀断に掻甚したす。
📡 耇数のトランスポヌトモヌド
  • Streamable-HTTP掚奚ストリヌミング察応のリク゚ストレスポンスボディを備えた最新の HTTP トランスポヌトで、HTTP ベヌスの MCP クラむアントに最適です。
  • Server-Sent EventsSSEリアルタむムストリヌミングにサヌバヌ送信むベントを䜿甚する埓来の HTTP トランスポヌトです。
  • 暙準入出力stdio組み蟌み統合向けの盎接的なプロセス間通信です。
  • リアルタむムストリヌミングすべおの HTTP トランスポヌトで、LLM の応答をトヌクン単䜍で曎新したす。
  • 進捗モニタリング長時間実行されるゞョブチャンク分割、バッチ凊理の進捗を远跡したす。
  • むベントベヌスのアヌキテクチャ特定のサヌバヌむベントを賌読できたす。
✹ 耇数モデルの統合
  • 比范分析耇数のモデルの出力を䞊べお分析したす。
  • 応答の統合最適な芁玠を組み合わせ、メタ応答を生成し、合意に基づく出力を䜜成したす。
  • 協調的な掚論異なるモデルがそれぞれ異なるステップを担圓するワヌクフロヌを実装したす。
🧩 モデル察応の拡匵
  • Grok 統合xAI の Grok をネむティブにサポヌトしたす。
  • DeepSeek 察応DeepSeek モデルに最適化された凊理を提䟛したす。
  • OpenRouter 統合OpenRouter API キヌを䜿甚しお、幅広いモデルにアクセスできたす。
  • ロヌカルセルフホスト統合OpenAI 互換の任意のロヌカルサヌバヌOllama、llama.cpp の llama-server、mistral.rs、vLLM、LM Studio向けに、蚭定可胜な単䞀の local プロバむダヌを利甚できたす。base_url を指定すれば、独自のハヌドりェア䞊で無料コスト $0の掚論を実行できたす。
  • Gemini 統合Google の Gemini モデルを包括的にサポヌトしたす。
  • Anthropic 統合Claude 3.5 Sonnet や Haiku を含む Claude モデルを完党にサポヌトしたす。
  • OpenAI 統合GPT-3.5、GPT-4.0、および新しいモデルを完党にサポヌトしたす。
🔧 自己改善ず動的統合のためのメタツヌル
  • ツヌルの怜出゚ヌゞェントは、利甚可胜なツヌル、パラメヌタヌ、説明を照䌚できたすlist_tools。
  • 䜿甚方法の掚奚タスクに適したツヌルの遞択や組み合わせに぀いお、AI によるアドバむスを受けられたす。
  • 倖郚 API 統合OpenAPI 仕様を介しお REST API を動的に登録し、゚ンドポむントを呌び出し可胜な MCP ツヌルずしお利甚できたすregister_api、call_dynamic_tool。
  • ドキュメントの生成Autonomous Refiner 機胜の䞀郚です。
📊 分析ずレポヌト
  • 䜿甚状況の远跡プロバむダヌモデルツヌルごずに、トヌクン数、コスト、リク゚スト数、成功率゚ラヌ率を監芖したす。
  • リアルタむムモニタリング䜿甚状況の統蚈をラむブダッシュボヌドたたはストリヌムで衚瀺したす。
  • 詳现なレポヌト過去のコスト䜿甚状況レポヌトを生成し、傟向を特定しお、デヌタを゚クスポヌトしたす。
  • 最適化の分析情報コストの高い凊理や非効率なパタヌンの特定に圹立ちたす。
📜 プロンプトテンプレヌトず管理
  • Jinja2 テンプレヌト倉数、条件分岐、むンクルヌドを䜿甚しお、再利甚可胜で動的なプロンプトを䜜成できたす。
  • プロンプトリポゞトリプロンプトを保存、取埗、分類し、バヌゞョン管理できたす。
  • メタデヌタテンプレヌトに説明、䜜成者、䜿甚䟋を远加できたす。
  • 最適化テンプレヌトのパフォヌマンスずトヌクン䜿甚量をテストしお比范できたす。
🛡 ゚ラヌ凊理ず回埩性
  • むンテリゞェントな再詊行䞀時的な゚ラヌレヌト制限、ネットワヌクの問題などが発生した堎合、指数バックオフで自動的に再詊行したす。
  • フォヌルバック機構プラむマリプロバむダヌに障害が発生した堎合のフォヌルバック先を蚭定できたす。
  • 詳现な゚ラヌ報告デバッグに圹立぀包括的な゚ラヌコンテキストを蚘録したす。
  • 入力怜蚌よくある問題トヌクン制限、必須パラメヌタヌなどを事前にチェックしたす。
⚙ システム機胜
  • 充実したログ機胜Rich を䜿甚しお、カラフルでわかりやすいコン゜ヌルログを衚瀺したす。
  • ヘルスモニタリング準備状態を確認するための /healthz ゚ンドポむント。
  • コマンドラむンむンタヌフェヌス管理や操䜜に䜿甚する umcp CLI。

📊 はじめに

🧪 むンストヌル
# Install uv (fast Python package manager) if you don't have it:
curl -LsSf https://astral.sh/uv/install.sh | sh

# Clone the repository
git clone https://github.com/Dicklesworthstone/ultimate_mcp_server.git
cd ultimate_mcp_server

# Create a virtual environment and install dependencies using uv:
uv venv --python 3.13
source .venv/bin/activate
uv lock --upgrade
uv sync --all-extras

泚uv sync --all-extras コマンドは、プロゞェクトで定矩されおいるすべおのオプションの远加機胜OCR、ブラりザヌ自動化、Excel などをむンストヌルしたす。特定の远加機胜のみが必芁な堎合は、プロゞェクトの䟝存関係を調敎し、--all-extras を指定せずに uv sync を実行しおください。

⚙ .env の蚭定

クロヌンしたリポゞトリのルヌトディレクトリに .env ずいう名前のファむルを䜜成したす。API キヌず、必芁に応じお蚭定の䞊曞きを远加しおください。

# --- API Keys (at least one provider required) ---
OPENAI_API_KEY=your_openai_sk-...
ANTHROPIC_API_KEY=your_anthropic_sk-...
GEMINI_API_KEY=your_google_ai_studio_key... # For Google AI Studio (Gemini API)
# Or use GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service-account-key.json for Vertex AI
DEEPSEEK_API_KEY=your_deepseek_key...
OPENROUTER_API_KEY=your_openrouter_key...
GROK_API_KEY=your_grok_key... # For Grok via xAI API

# --- Local / Self-Hosted Providers (OpenAI-compatible, FREE inference) ---
# One generic provider covers Ollama, llama.cpp (llama-server), mistral.rs, vLLM, and LM Studio.
# No API key is required by most local servers; LOCAL_LLM_API_KEY is optional.
# LOCAL_LLM_BASE_URL=http://localhost:11434/v1   # Default (Ollama). Examples:
#   llama.cpp / mistral.rs / vLLM : http://localhost:8000/v1
#   LM Studio                     : http://localhost:1234/v1
# LOCAL_LLM_DEFAULT_MODEL=llama3.1:8b            # Model name as served by your local backend
# LOCAL_LLM_API_KEY=                             # Optional; most local servers ignore it
# LOCAL_LLM_REQUEST_TIMEOUT=30                   # Optional request timeout in seconds
# LOCAL_LLM_ENABLED=true                         # Optional; set false to disable the local provider

# --- Server Configuration (Defaults shown) ---
GATEWAY_SERVER_PORT=8013
GATEWAY_SERVER_HOST=127.0.0.1 # Change to 0.0.0.0 to listen on all interfaces (needed for Docker/external access)
# GATEWAY_API_PREFIX=/

# --- Logging Configuration (Defaults shown) ---
LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR, CRITICAL
USE_RICH_LOGGING=true # Set to false for plain text logs

# --- Cache Configuration (Defaults shown) ---
GATEWAY_CACHE_ENABLED=true
GATEWAY_CACHE_TTL=86400 # Default Time-To-Live in seconds (24 hours)
# GATEWAY_CACHE_TYPE=memory # Options might include 'memory', 'redis', 'diskcache' (check implementation)
# GATEWAY_CACHE_MAX_SIZE=1000 # Example: Max number of items for memory cache
# GATEWAY_CACHE_DIR=./.cache # Directory for disk cache storage

# --- Provider Timeouts & Retries (Defaults shown) ---
# GATEWAY_PROVIDER_TIMEOUT=120 # Default timeout in seconds for API calls
# GATEWAY_PROVIDER_MAX_RETRIES=3 # Default max retries on failure

# --- Provider-Specific Configuration ---
# GATEWAY_OPENAI_DEFAULT_MODEL=gpt-4.1-mini # Customize default model
# GATEWAY_ANTHROPIC_DEFAULT_MODEL=claude-3-5-sonnet-20241022 # Customize default model
# GATEWAY_GEMINI_DEFAULT_MODEL=gemini-2.0-pro # Customize default model

# --- Tool Specific Config (Examples) ---
# FILESYSTEM__ALLOWED_DIRECTORIES=["/path/to/safe/dir1","/path/to/safe/dir2"] # For Filesystem tools (JSON array)
# GATEWAY_AGENT_MEMORY_DB_PATH=unified_agent_memory.db # Path for agent memory database
# GATEWAY_PROMPT_TEMPLATES_DIR=./prompt_templates # Directory for prompt templates
▶ 実行

仮想環境が有効になっおいるこずを確認しおくださいsource .venv/bin/activate。

# Start the MCP server with all registered tools found
umcp run

# Start the server including only specific tools
umcp run --include-tools completion chunk_document read_file write_file

# Start the server excluding specific tools
umcp run --exclude-tools browser_init browser_navigate research_and_synthesize_report

# Start with Docker (ensure .env file exists in the project root or pass environment variables)
docker compose up --build # Add --build the first time or after changes

起動するず、通垞、サヌバヌは http://localhost:8013たたは .env もしくはコマンドラむンで蚭定したホストポヌトで利甚できたす。サヌバヌの起動ず登録枈みツヌルを瀺すログが衚瀺されたす。

💻 コマンドラむンむンタヌフェヌスCLI

Ultimate MCP Server には、サヌバヌの管理、LLM プロバむダヌずのやり取り、機胜のテスト、サンプルの確認を行える匷力なコマンドラむンむンタヌフェヌスCLIが umcp コマンドで甚意されおいたす。このセクションでは、利甚可胜なすべおのコマンドずオプションに぀いお説明したす。

🌟 グロヌバルオプション

umcp コマンドでは、次のグロヌバルオプションを䜿甚できたす。

umcp --version  # Display version information
🚀 サヌバヌ管理
サヌバヌの起動

run コマンドは、指定したオプションで Ultimate MCP Server を起動したす。

# Basic server start with default settings from .env
umcp run

# Run on a specific host (-h) and port (-p)
umcp run -h 0.0.0.0 -p 9000

# Run with multiple worker processes (-w)
umcp run -w 4

# Enable debug logging (-d)
umcp run -d

# Use stdio transport (-t)
umcp run -t stdio

# Use streamable-http transport (recommended for HTTP clients)
umcp run -t shttp

# Run only with specific tools (no shortcut for --include-tools)
umcp run --include-tools completion chunk_document read_file write_file

# Run with all tools except certain ones (no shortcut for --exclude-tools)
umcp run --exclude-tools browser_init browser_navigate

出力䟋

┌─ Starting Ultimate MCP Server ───────────────────┐
│ Host: 0.0.0.0                                    │
│ Port: 9000                                       │
│ Workers: 4                                       │
│ Transport mode: streamable-http                  │
└────────────────────────────────────────────────┘

INFO:     Started server process [12345]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit)

利甚可胜なオプション

  • -h, --hostサヌバヌをバむンドするホスト名たたは IP アドレスデフォルト.env の倀
  • -p, --portリッスンするポヌトデフォルト.env の倀
  • -w, --workers起動するワヌカヌプロセス数デフォルト.env の倀
  • -t, --transport-modeサヌバヌ通信のトランスポヌトモヌドストリヌミング可胜な HTTP は 'shttp'、たたは 'sse'、'stdio'。デフォルトshttp
  • -d, --debugデバッグログを有効にしたす
  • --include-tools含めるツヌル名のリストカンマ区切り
  • --exclude-tools陀倖するツヌル名のリストカンマ区切り
🔌 プロバむダヌ管理
プロバむダヌの䞀芧衚瀺

providers コマンドは、蚭定枈みの LLM プロバむダヌに関する情報を衚瀺したす。

# List all configured providers
umcp providers

# Check API keys (-c) for all configured providers
umcp providers -c

# List available models (no shortcut for --models)
umcp providers --models

# Check keys and list models
umcp providers -c --models

出力䟋

┌─ LLM Providers ──────────────────────────────────────────────────┐
│ Provider   Status   Default Model            API Key             │
├────────────────────────────────────────────────────────────────────
│ openai     ✓        gpt-4.1-mini            sk-...5vX [VALID]    │
│ anthropic  ✓        claude-3-5-sonnet-20241022 sk-...Hr [VALID]  │
│ gemini     ✓        gemini-2.0-pro          [VALID]              │
│ deepseek   ✗        deepseek-chat           [NOT CONFIGURED]     │
│ openrouter ✓        --                      [VALID]              │
│ grok       ✓        grok-1                  [VALID]              │
└───────────────────────────────────────────────────────────────────┘

--models を指定した堎合

OPENAI MODELS:
  - gpt-4.1-mini
  - gpt-4o
  - gpt-4-0125-preview
  - gpt-3.5-turbo

ANTHROPIC MODELS:
  - claude-3-5-sonnet-20241022
  - claude-3-5-haiku-20241022
  - claude-3-opus-20240229
  ...

利甚可胜なオプション

  • -c, --check蚭定枈みのすべおのプロバむダヌの API キヌを確認したす
  • --models各プロバむダヌで利甚可胜なモデルを䞀芧衚瀺したす
プロバむダヌのテスト

test コマンドを䜿甚しお、特定のプロバむダヌをテストできたす。

# Test the default OpenAI model with a simple prompt
umcp test openai

# Test a specific model (--model) with a custom prompt (--prompt)
umcp test anthropic --model claude-3-5-haiku-20241022 --prompt "Write a short poem about coding."

# Test Gemini with a different prompt
umcp test gemini --prompt "What are three interesting AI research papers from 2024?"

出力䟋

Testing provider 'anthropic'...

Provider: anthropic
Model: claude-3-5-haiku-20241022
Prompt: Write a short poem about coding.

❯ Response:
Code flows like water,
Logic cascades through the mind—
Bugs bloom like flowers.

Tokens: 13 input, 19 output
Cost: $0.00006
Response time: 0.82s

利甚可胜なオプション

  • --modelテストするモデル IDデフォルトではプロバむダヌのデフォルトを䜿甚したす
  • --prompt送信するプロンプトテキストデフォルト「Hello, world!」
⚡ テキストの盎接生成

complete コマンドを䜿うず、CLI からテキストを盎接生成できたす。

# Generate text with default provider (OpenAI) using a prompt (--prompt)
umcp complete --prompt "Write a concise explanation of quantum computing."

# Specify a provider (--provider) and model (--model)
umcp complete --provider anthropic --model claude-3-5-sonnet-20241022 --prompt "What are the key differences between Rust and Go?"

# Use a system prompt (--system)
umcp complete --provider openai --model gpt-4o --system "You are an expert programmer..." --prompt "Explain dependency injection."

# Stream the response token by token (-s)
umcp complete --provider openai --prompt "Count from 1 to 10." -s

# Adjust temperature (--temperature) and token limit (--max-tokens)
umcp complete --provider gemini --temperature 1.2 --max-tokens 250 --prompt "Generate a creative sci-fi story opening."

# Read prompt from stdin (no --prompt needed)
echo "Tell me about space exploration." | umcp complete

出力䟋

Quantum computing uses quantum bits (qubits) that can exist in multiple states simultaneously, unlike classical bits (0 or 1). This quantum superposition, along with entanglement, allows quantum computers to process vast amounts of information in parallel, potentially solving certain complex problems exponentially faster than classical computers. Applications include cryptography, materials science, and optimization problems.

Tokens: 13 input, 72 output
Cost: $0.00006
Response time: 0.37s

利甚可胜なオプション

  • --provider䜿甚するプロバむダヌデフォルトopenai
  • --modelモデル IDデフォルトはプロバむダヌの既定倀
  • --promptプロンプトのテキスト指定しない堎合は stdin から読み蟌みたす
  • --temperatureサンプリング枩床0.02.0、デフォルト0.7
  • --max-tokens生成する最倧トヌクン数
  • --system察応するプロバむダヌ向けのシステムプロンプト
  • -s, --stream応答をトヌクンごずにストリヌミングしたす
💟 キャッシュ管理

cache コマンドを䜿うず、リク゚ストキャッシュの衚瀺や消去ができたす。

# Show cache status (default action)
umcp cache

# Explicitly show status (no shortcut for --status)
umcp cache --status

# Clear the cache (no shortcut for --clear, with confirmation prompt)
umcp cache --clear

# Show stats and clear the cache in one command
umcp cache --status --clear

出力䟋

Cache Status:
  Backend: memory
  Enabled: True
  Items: 127
  Hit rate: 73.2%
  Estimated savings: $1.47

利甚可胜なオプション

  • --statusキャッシュの状態を衚瀺したすほかのフラグが指定されおいない堎合はデフォルト
  • --clearキャッシュを消去したす確認を求めたす
📊 ベンチマヌク

benchmark コマンドを䜿うず、プロバむダヌ間のパフォヌマンスずコストを比范できたす。

# Run default benchmark (3 runs per provider)
umcp benchmark

# Benchmark only specific providers
umcp benchmark --providers openai,anthropic

# Benchmark with specific models
umcp benchmark --providers openai,anthropic --models gpt-4o,claude-3.5-sonnet

# Use a custom prompt and more runs (-r)
umcp benchmark --prompt "Explain the process of photosynthesis in detail." -r 5

出力䟋

┌─ Benchmark Results ───────────────────────────────────────────────────────┐
│ Provider    Model               Avg Time   Tokens    Cost      Tokens/sec │
├───────────────────────────────────────────────────────────────────────────
│ openai      gpt-4.1-mini        0.47s      76 / 213  $0.00023  454        │
│ anthropic   claude-3-5-haiku    0.52s      76 / 186  $0.00012  358        │
│ gemini      gemini-2.0-pro      0.64s      76 / 201  $0.00010  314        │
│ deepseek    deepseek-chat       0.71s      76 / 195  $0.00006  275        │
└──────────────────────────────────────────────────────────────────────────┘

利甚可胜なオプション

  • --providersベンチマヌク察象のプロバむダヌ䞀芧デフォルト蚭定枈みのすべお
  • --modelsベンチマヌク察象のモデル IDデフォルトは各プロバむダヌの既定モデル
  • --prompt䜿甚するプロンプトのテキストデフォルト組み蟌みのベンチマヌク甚プロンプト
  • -r, --runsプロバむダヌモデルごずの実行回数デフォルト3
🧰 ツヌル管理

tools コマンドは、利甚可胜なツヌルを䞀芧衚瀺したす。カテゎリで絞り蟌むこずもできたす。

# List all tools
umcp tools

# List tools in a specific category
umcp tools --category document

# Show related example scripts
umcp tools --examples

出力䟋

┌─ Ultimate MCP Server Tools ─────────────────────────────────────────┐
│ Category    Tool                           Example Script            │
├───────────────────────────────────────────────────────────────────────
│ completion  generate_completion            simple_completion_demo.py │
│ completion  stream_completion              simple_completion_demo.py │
│ completion  chat_completion                claude_integration_demo.py│
│ document    summarize_document             document_processing.py    │
│ document    chunk_document                 document_processing.py    │
│ extraction  extract_json                   advanced_extraction_demo.py│
│ filesystem  read_file                      filesystem_operations_demo.py│
└──────────────────────────────────────────────────────────────────────┘

Tip: Run examples using the command:
  umcp examples <example_name>

利甚可胜なオプション

  • --categoryカテゎリでツヌルを絞り蟌みたす
  • --examplesツヌルずずもにサンプルスクリプトを衚瀺したす
📚 サンプル管理

examples コマンドを䜿うず、サンプルスクリプトの䞀芧衚瀺や実行ができたす。

# List all example scripts (default action)
umcp examples

# Explicitly list example scripts (-l)
umcp examples -l

# Run a specific example
umcp examples rag_example.py

# Can also run by just the name without extension
umcp examples rag_example

䞀芧衚瀺時の出力䟋

┌─ Ultimate MCP Server Example Scripts ─────────────────────────────────┐
│ Category             Example Script                                   │
├─────────────────────────────────────────────────────────────────────────
│ text-generation      simple_completion_demo.py                        │
│ text-generation      claude_integration_demo.py                       │
│ document-processing  document_processing.py                           │
│ search-and-retrieval rag_example.py                                   │
│ browser-automation   browser_automation_demo.py                       │
└────────────────────────────────────────────────────────────────────────┘

Run an example:
  umcp examples <example_name>

サンプルの実行時

Running example: rag_example.py

Creating vector knowledge base 'demo_kb'...
Adding sample documents...
Retrieving context for query: "What are the benefits of clean energy?"
Generated response:
Based on the retrieved context, clean energy offers several benefits:
...

利甚可胜なオプション

  • -l, --listサンプルスクリプトのみを䞀芧衚瀺したす
  • --categoryカテゎリでサンプルを絞り蟌みたす
🔎 ヘルプの衚瀺

各コマンドには詳现なヘルプが甚意されおいたす。

# General help
umcp --help

# Help for a specific command
umcp run --help
umcp providers --help
umcp complete --help

出力䟋

Usage: umcp [OPTIONS] COMMAND [ARGS]...

  Ultimate MCP Server: Multi-provider LLM management server
  Unified CLI to run your server, manage providers, and more.

Options:
  --version, -v                   Show the application version and exit.
  --help                          Show this message and exit.

Commands:
  run          Run the Ultimate MCP Server
  providers    List Available Providers
  test         Test a Specific Provider
  complete     Generate Text Completion
  cache        Cache Management
  benchmark    Benchmark Providers
  tools        List Available Tools
  examples     Run or List Example Scripts

コマンド固有のヘルプ

Usage: umcp run [OPTIONS]

  Run the Ultimate MCP Server

  Start the server with optional overrides.

  Examples:
    umcp run -h 0.0.0.0 -p 8000 -w 4 -t sse
    umcp run -d

Options:
  -h, --host TEXT                 Host or IP address to bind the server to.
                                  Defaults from config.
  -p, --port INTEGER              Port to listen on. Defaults from config.
  -w, --workers INTEGER           Number of worker processes to spawn.
                                  Defaults from config.
  -t, --transport-mode [shttp|sse|stdio]
                                  Transport mode for server communication (-t
                                  shortcut). Options: 'shttp' (streamable-http, 
                                  recommended), 'sse', or 'stdio'.
  -d, --debug                     Enable debug logging for detailed output (-d
                                  shortcut).
  --include-tools TEXT            List of tool names to include when running
                                  the server.
  --exclude-tools TEXT            List of tool names to exclude when running
                                  the server.
  --help                          Show this message and exit.

🧪 䜿甚䟋

このセクションでは、実行䞭の Ultimate MCP Server むンスタンスが提䟛するツヌルを、MCP クラむアントmcp-client を䜿うアプリケヌションなどや Claude のような゚ヌゞェントがどのように利甚するかを瀺す Python の䟋を玹介したす。

泚これらの䟋では、mcp-client がむンストヌル枈みpip install mcp-clientで、Ultimate MCP Server が http://localhost:8013 で実行䞭であるこずを前提ずしおいたす。

(詳现なコヌドブロックは、完党性を保぀ため、元の入力のたた以䞋に蚘茉しおいたす)

基本的なテキスト生成
import asyncio
from mcp.client import Client

async def basic_completion_example():
    client = Client("http://localhost:8013")
    response = await client.tools.completion(
        prompt="Write a short poem about a robot learning to dream.",
        provider="openai",
        model="gpt-4.1-mini",
        max_tokens=100,
        temperature=0.7
    )
    if response["success"]:
        print(f"Completion: {response['completion']}")
        print(f"Cost: ${response['cost']:.6f}")
    else:
        print(f"Error: {response['error']}")
    await client.close()

# if __name__ == "__main__": asyncio.run(basic_completion_example())
Claude による Ultimate MCP Server を䜿ったドキュメント分析委任
import asyncio
from mcp.client import Client

async def document_analysis_example():
    # Assume Claude identifies a large document needing processing
    client = Client("http://localhost:8013")
    document = "... large document content ..." * 100 # Placeholder for large content

    print("Delegating document chunking...")
    # Step 1: Claude delegates document chunking (often a local, non-LLM task on server)
    chunks_response = await client.tools.chunk_document(
        document=document,
        chunk_size=1000, # Target tokens per chunk
        overlap=100,     # Token overlap
        method="semantic" # Use semantic chunking if available
    )
    if not chunks_response["success"]:
        print(f"Chunking failed: {chunks_response['error']}")
        await client.close()
        return

    print(f"Document divided into {chunks_response['chunk_count']} chunks.")

    # Step 2: Claude delegates summarization of each chunk to a cheaper model
    summaries = []
    total_cost = 0.0
    print("Delegating chunk summarization to gemini-2.0-flash-lite...")
    for i, chunk in enumerate(chunks_response["chunks"]):
        # Use Gemini Flash (much cheaper than Claude or GPT-4o) via the server
        summary_response = await client.tools.summarize_document(
            document=chunk,
            provider="gemini", # Explicitly delegate to Gemini via server
            model="gemini-2.0-flash-lite",
            format="paragraph",
            max_length=150 # Request a concise summary
        )
        if summary_response["success"]:
            summaries.append(summary_response["summary"])
            cost = summary_response.get("cost", 0.0)
            total_cost += cost
            print(f"  Processed chunk {i+1}/{chunks_response['chunk_count']} summary. Cost: ${cost:.6f}")
        else:
            print(f"  Chunk {i+1} summarization failed: {summary_response['error']}")

    print("\nDelegating entity extraction to gpt-4.1-mini...")
    # Step 3: Claude delegates entity extraction for the whole document to another cheap model
    entities_response = await client.tools.extract_entities(
        document=document, # Process the original document
        entity_types=["person", "organization", "location", "date", "product"],
        provider="openai", # Delegate to OpenAI's cheaper model
        model="gpt-4.1-mini"
    )

    if entities_response["success"]:
        cost = entities_response.get("cost", 0.0)
        total_cost += cost
        print(f"Extracted entities. Cost: ${cost:.6f}")
        extracted_entities = entities_response['entities']
        # Claude would now process these summaries and entities using its advanced capabilities
        print(f"\nClaude can now use {len(summaries)} summaries and {len(extracted_entities)} entity groups.")
    else:
        print(f"Entity extraction failed: {entities_response['error']}")

    print(f"\nTotal estimated delegation cost for sub-tasks: ${total_cost:.6f}")

    # Claude might perform final synthesis using the collected results
    final_synthesis_prompt = f"""
Synthesize the key information from the following summaries and entities extracted from a large document.
Focus on the main topics, key people involved, and significant events mentioned.

Summaries:
{' '.join(summaries)}

Entities:
{extracted_entities}

Provide a concise final report.
"""
    # This final step would likely use Claude itself (not shown here)

    await client.close()

# if __name__ == "__main__": asyncio.run(document_analysis_example())
調査のためのブラりザヌ自動化
import asyncio
from mcp.client import Client

async def browser_research_example():
    client = Client("http://localhost:8013")
    print("Starting browser-based research task...")
    # This tool likely orchestrates multiple browser actions (search, navigate, scrape)
    # and uses an LLM (specified or default) for synthesis.
    result = await client.tools.research_and_synthesize_report(
        topic="Latest advances in AI-powered drug discovery using graph neural networks",
        instructions={
            "search_query": "graph neural networks drug discovery 2024 research",
            "search_engines": ["google", "duckduckgo"], # Use multiple search engines
            "urls_to_include": ["nature.com", "sciencemag.org", "arxiv.org", "pubmed.ncbi.nlm.nih.gov"], # Prioritize these domains
            "max_urls_to_process": 7, # Limit the number of pages to visit/scrape
            "min_content_length": 500, # Ignore pages with very little content
            "focus_areas": ["novel molecular structures", "binding affinity prediction", "clinical trial results"], # Guide the synthesis
            "report_format": "markdown", # Desired output format
            "report_length": "detailed", # comprehensive, detailed, summary
            "llm_model": "anthropic/claude-3-5-sonnet-20241022" # Specify LLM for synthesis
        }
    )

    if result["success"]:
        print("\nResearch report generated successfully!")
        print(f"Processed {len(result.get('extracted_data', []))} sources.")
        print(f"Total processing time: {result.get('processing_time', 'N/A'):.2f}s")
        print(f"Estimated cost: ${result.get('total_cost', 0.0):.6f}") # Includes LLM synthesis cost
        print("\n--- Research Report ---")
        print(result['report'])
        print("-----------------------")
    else:
        print(f"\nBrowser research failed: {result.get('error', 'Unknown error')}")
        if 'details' in result: print(f"Details: {result['details']}")

    await client.close()

# if __name__ == "__main__": asyncio.run(browser_research_example())
認知メモリヌシステムの䜿甚
import asyncio
from mcp.client import Client
import uuid

async def cognitive_memory_example():
    client = Client("http://localhost:8013")
    # Generate a unique ID for this session/workflow if not provided
    workflow_id = str(uuid.uuid4())
    print(f"Using Workflow ID: {workflow_id}")

    print("\nCreating a workflow context...")
    # Create a workflow context to group related memories and actions
    workflow_response = await client.tools.create_workflow(
        workflow_id=workflow_id,
        title="Quantum Computing Investment Analysis",
        description="Analyzing the impact of quantum computing on financial markets.",
        goal="Identify potential investment opportunities or risks."
    )
    if not workflow_response["success"]: print(f"Error creating workflow: {workflow_response['error']}")

    print("\nRecording an agent action...")
    # Record the start of a research action
    action_response = await client.tools.record_action_start(
        workflow_id=workflow_id,
        action_type="research",
        title="Initial literature review on quantum algorithms in finance",
        reasoning="Need to understand the current state-of-the-art before assessing impact."
    )
    action_id = action_response.get("action_id") if action_response["success"] else None
    if not action_id: print(f"Error starting action: {action_response['error']}")

    print("\nStoring facts in semantic memory...")
    # Store some key facts discovered during research
    memory1 = await client.tools.store_memory(
        workflow_id=workflow_id,
        content="Shor's algorithm can break RSA encryption, posing a threat to current financial security.",
        memory_type="fact", memory_level="semantic", importance=9.0,
        tags=["quantum_algorithm", "cryptography", "risk", "shor"]
    )
    memory2 = await client.tools.store_memory(
        workflow_id=workflow_id,
        content="Quantum annealing (e.g., D-Wave) shows promise for portfolio optimization problems.",
        memory_type="fact", memory_level="semantic", importance=7.5,
        tags=["quantum_computing", "finance", "optimization", "annealing"]
    )
    if memory1["success"]: print(f"Stored memory ID: {memory1['memory_id']}")
    if memory2["success"]: print(f"Stored memory ID: {memory2['memory_id']}")

    print("\nStoring an observation (episodic memory)...")
    # Store an observation from a specific event/document
    obs_memory = await client.tools.store_memory(
        workflow_id=workflow_id,
        content="Read Nature article (doi:...) suggesting experimental quantum advantage in a specific financial modeling task.",
        memory_type="observation", memory_level="episodic", importance=8.0,
        source="Nature Article XYZ", timestamp="2024-07-20T10:00:00Z", # Example timestamp
        tags=["research_finding", "publication", "finance_modeling"]
    )
    if obs_memory["success"]: print(f"Stored episodic memory ID: {obs_memory['memory_id']}")

    print("\nSearching for relevant memories...")
    # Search for memories related to financial risks
    search_results = await client.tools.hybrid_search_memories(
        workflow_id=workflow_id,
        query="What are the financial risks associated with quantum computing?",
        top_k=5, memory_type="fact", # Search for facts first
        semantic_weight=0.7, keyword_weight=0.3 # Example weighting for hybrid search
    )
    if search_results["success"]:
        print(f"Found {len(search_results['results'])} relevant memories:")
        for res in search_results["results"]:
            print(f"  - Score: {res['score']:.4f}, ID: {res['memory_id']}, Content: {res['content'][:80]}...")
    else:
        print(f"Memory search failed: {search_results['error']}")

    print("\nGenerating a reflection based on stored memories...")
    # Generate insights or reflections based on the accumulated knowledge in the workflow
    reflection_response = await client.tools.generate_reflection(
        workflow_id=workflow_id,
        reflection_type="summary_and_next_steps", # e.g., insights, risks, opportunities
        context_query="Summarize the key findings about quantum finance impact and suggest next research actions."
    )
    if reflection_response["success"]:
        print("Generated Reflection:")
        print(reflection_response["reflection"])
    else:
        print(f"Reflection generation failed: {reflection_response['error']}")

    # Mark the action as completed (assuming research phase is done)
    if action_id:
        print("\nCompleting the research action...")
        await client.tools.record_action_end(
            workflow_id=workflow_id, action_id=action_id, status="completed",
            outcome="Gathered initial understanding of quantum algorithms in finance and associated risks."
        )

    await client.close()

# if __name__ == "__main__": asyncio.run(cognitive_memory_example())
Excel スプレッドシヌトの自動化
import asyncio
from mcp.client import Client
import os

async def excel_automation_example():
    client = Client("http://localhost:8013")
    output_dir = "excel_outputs"
    os.makedirs(output_dir, exist_ok=True)
    output_path = os.path.join(output_dir, "financial_model.xlsx")

    print(f"Requesting creation of Excel financial model at {output_path}...")
    # Example: Create a financial model using natural language instructions
    create_result = await client.tools.excel_execute(
        instruction="Create a simple 3-year financial projection.\n"
                   "Sheet name: 'Projections'.\n"
                   "Columns: Year 1, Year 2, Year 3.\n"
                   "Rows: Revenue, COGS, Gross Profit, Operating Expenses, Net Income.\n"
                   "Data: Start Revenue at $100,000, grows 20% annually.\n"
                   "COGS is 40% of Revenue.\n"
                   "Operating Expenses start at $30,000, grow 10% annually.\n"
                   "Calculate Gross Profit (Revenue - COGS) and Net Income (Gross Profit - OpEx).\n"
                   "Format currency as $#,##0. Apply bold headers and add a light blue fill to the header row.",
        file_path=output_path, # Server needs write access to this path/directory if relative
        operation_type="create", # create, modify, analyze, format
        # sheet_name="Projections", # Can specify sheet if modifying
        # cell_range="A1:D6", # Can specify range
        show_excel=False # Run Excel in the background (if applicable on the server)
    )

    if create_result["success"]:
        print(f"Excel creation successful: {create_result['message']}")
        print(f"File saved at: {create_result.get('output_file_path', output_path)}") # Confirm output path

        # Example: Modify the created file - add a chart
        print("\nRequesting modification: Add a Revenue chart...")
        modify_result = await client.tools.excel_execute(
            instruction="Add a column chart showing Revenue for Year 1, Year 2, Year 3. "
                       "Place it below the table. Title the chart 'Revenue Projection'.",
            file_path=output_path, # Use the previously created file
            operation_type="modify",
            sheet_name="Projections" # Specify the sheet to modify
        )
        if modify_result["success"]:
             print(f"Excel modification successful: {modify_result['message']}")
             print(f"File updated at: {modify_result.get('output_file_path', output_path)}")
        else:
             print(f"Excel modification failed: {modify_result['error']}")

    else:
        print(f"Excel creation failed: {create_result['error']}")
        if 'details' in create_result: print(f"Details: {create_result['details']}")

    # Example: Analyze formulas (if the tool supports it)
    # analysis_result = await client.tools.excel_analyze_formulas(...)

    await client.close()

# if __name__ == "__main__": asyncio.run(excel_automation_example())
耇数プロバむダヌの比范
import asyncio
from mcp.client import Client

async def multi_provider_completion_example():
    client = Client("http://localhost:8013")
    prompt = "Explain the concept of 'Chain of Thought' prompting for Large Language Models."

    print(f"Requesting completions for prompt: '{prompt}' from multiple providers...")
    # Request the same prompt from different models/providers
    multi_response = await client.tools.multi_completion(
        prompt=prompt,
        providers=[
            {"provider": "openai", "model": "gpt-4.1-mini", "temperature": 0.5},
            {"provider": "anthropic", "model": "claude-3-5-sonnet-20241022", "temperature": 0.5},
            {"provider": "gemini", "model": "gemini-2.0-pro", "temperature": 0.5},
            # {"provider": "deepseek", "model": "deepseek-chat", "temperature": 0.5}, # Add others if configured
        ],
        # Common parameters applied to all if not specified per provider
        max_tokens=300
    )

    if multi_response["success"]:
        print("\n--- Multi-completion Results ---")
        total_cost = multi_response.get("total_cost", 0.0)
        print(f"Total Estimated Cost: ${total_cost:.6f}\n")

        for provider_key, result in multi_response["results"].items():
            print(f"--- Provider: {provider_key} ---")
            if result["success"]:
                print(f"  Model: {result.get('model', 'N/A')}")
                print(f"  Cost: ${result.get('cost', 0.0):.6f}")
                print(f"  Tokens: Input={result.get('input_tokens', 'N/A')}, Output={result.get('output_tokens', 'N/A')}")
                print(f"  Completion:\n{result['completion']}\n")
            else:
                print(f"  Error: {result['error']}\n")
        print("------------------------------")
        # An agent could now analyze these responses for consistency, detail, accuracy etc.
    else:
        print(f"\nMulti-completion request failed: {multi_response['error']}")

    await client.close()

# if __name__ == "__main__": asyncio.run(multi_provider_completion_example())
コストを最適化したワヌクフロヌの実行
import asyncio
from mcp.client import Client

async def optimized_workflow_example():
    client = Client("http://localhost:8013")
    # Example document to process through the workflow
    document_content = """
    Project Alpha Report - Q3 2024
    Lead: Dr. Evelyn Reed ([email protected])
    Status: On Track
    Budget: $50,000 remaining. Spent $25,000 this quarter.
    Key Findings: Successful prototype development (v0.8). User testing feedback positive.
    Next Steps: Finalize documentation, prepare for Q4 deployment. Target date: 2024-11-15.
    Risks: Potential delay due to supplier issues for component X. Mitigation plan in place.
    """

    print("Defining a multi-stage workflow...")
    # Define a workflow with stages, dependencies, and provider preferences
    # Use ${stage_id.output_key} to pass outputs between stages
    workflow_definition = [
        {
            "stage_id": "summarize_report",
            "tool_name": "summarize_document",
            "params": {
                "document": document_content,
                "format": "bullet_points",
                "max_length": 100,
                # Let the server choose a cost-effective model for summarization
                "provider_preference": "cost", # 'cost', 'quality', 'speed', or specific like 'openai/gpt-4.1-mini'
            }
            # No 'depends_on', runs first
            # Default output key is 'summary' for this tool, access via ${summarize_report.summary}
        },
        {
            "stage_id": "extract_key_info",
            "tool_name": "extract_json", # Use JSON extraction for structured data
            "params": {
                "document": document_content,
                "json_schema": {
                    "type": "object",
                    "properties": {
                        "project_lead": {"type": "string"},
                        "lead_email": {"type": "string", "format": "email"},
                        "status": {"type": "string"},
                        "budget_remaining": {"type": "string"},
                        "next_milestone_date": {"type": "string", "format": "date"}
                    },
                    "required": ["project_lead", "status", "next_milestone_date"]
                },
                # Prefer a model known for good structured data extraction, balancing cost
                "provider_preference": "quality", # Prioritize quality for extraction
                "preferred_models": ["openai/gpt-4o", "anthropic/claude-3-5-sonnet-20241022"] # Suggest specific models
            }
        },
        {
            "stage_id": "generate_follow_up_questions",
            "tool_name": "generate_qa", # Assuming a tool that generates questions
            "depends_on": ["summarize_report"], # Needs the summary first
            "params": {
                # Use the summary from the first stage as input
                "document": "${summarize_report.summary}",
                "num_questions": 3,
                "provider_preference": "speed" # Use a fast model for question generation
            }
            # Default output key 'qa_pairs', access via ${generate_follow_up_questions.qa_pairs}
        }
    ]

    print("Executing the optimized workflow...")
    # Execute the workflow - the server handles dependencies and model selection
    results = await client.tools.execute_optimized_workflow(
        workflow=workflow_definition
        # Can also pass initial documents if workflow steps reference 'original_document'
        # documents = {"report.txt": document_content}
    )

    if results["success"]:
        print("\nWorkflow executed successfully!")
        print(f"  Total processing time: {results.get('processing_time', 'N/A'):.2f}s")
        print(f"  Total estimated cost: ${results.get('total_cost', 0.0):.6f}\n")

        print("--- Stage Outputs ---")
        for stage_id, output in results.get("stage_outputs", {}).items():
            print(f"Stage: {stage_id}")
            if output["success"]:
                print(f"  Provider/Model Used: {output.get('provider', 'N/A')}/{output.get('model', 'N/A')}")
                print(f"  Cost: ${output.get('cost', 0.0):.6f}")
                print(f"  Output: {output.get('result', 'N/A')}") # Access the primary result
                # You might access specific keys like output.get('result', {}).get('summary') etc.
            else:
                print(f"  Error: {output.get('error', 'Unknown error')}")
            print("-" * 20)

    else:
        print(f"\nWorkflow execution failed: {results.get('error', 'Unknown error')}")
        if 'details' in results: print(f"Details: {results['details']}")

    await client.close()

# if __name__ == "__main__": asyncio.run(optimized_workflow_example())
゚ンティティ関係グラフの䟋
import asyncio
from mcp.client import Client
# import networkx as nx # To process the graph data if needed
# import matplotlib.pyplot as plt # To visualize

async def entity_graph_example():
    client = Client("http://localhost:8013")
    document_text = """
    Meta Platforms, Inc., led by CEO Mark Zuckerberg, announced a partnership with IBM
    on developing new AI hardware accelerators. The collaboration aims to challenge Nvidia's dominance.
    IBM, headquartered in Armonk, New York, brings its deep expertise in semiconductor design.
    The project, codenamed 'Synergy', is expected to yield results by late 2025.
    """

    print("Extracting entity relationships from text...")
    # Request extraction of entities and their relationships
    entity_graph_response = await client.tools.extract_entity_relations(
        document=document_text,
        entity_types=["organization", "person", "location", "date", "project"], # Specify desired entity types
        relationship_types=["led_by", "partnership_with", "aims_to_challenge", "headquartered_in", "expected_by"], # Specify relationship types
        # Optional parameters:
        # provider_preference="quality", # Choose model strategy
        # llm_model="anthropic/claude-3-5-sonnet-20241022", # Suggest a specific model
        include_visualization=False # Set True to request image data if tool supports it
    )

    if entity_graph_response["success"]:
        print("Entity relationship extraction successful.")
        print(f"Estimated Cost: ${entity_graph_response.get('cost', 0.0):.6f}")

        # The graph data might be in various formats (e.g., node-link list, adjacency list)
        graph_data = entity_graph_response.get("graph_data")
        print("\n--- Graph Data (Nodes & Edges) ---")
        print(graph_data)
        print("------------------------------------")

        # Example: Query the extracted graph using another tool or LLM call
        # (Assuming a separate query tool or using a general completion tool)
        print("\nQuerying the extracted graph (example)...")
        query_prompt = f"""
Based on the following graph data representing relationships extracted from a text:
{graph_data}

Answer the question: Who is the CEO of Meta Platforms, Inc.?
"""
        query_response = await client.tools.completion(
             prompt=query_prompt, provider="openai", model="gpt-4.1-mini", max_tokens=50
        )
        if query_response["success"]:
             print(f"Graph Query Answer: {query_response['completion']}")
        else:
             print(f"Graph query failed: {query_response['error']}")


    else:
        print(f"Entity relationship extraction failed: {entity_graph_response.get('error', 'Unknown error')}")

    await client.close()

# if __name__ == "__main__": asyncio.run(entity_graph_example())
ドキュメントのチャンク分割
import asyncio
from mcp.client import Client

async def document_chunking_example():
    client = Client("http://localhost:8013")
    large_document = """
    This is the first paragraph of a potentially very long document. It discusses various concepts.
    The second paragraph continues the discussion, adding more details and nuances. Proper chunking
    is crucial for processing large texts with Large Language Models, especially those with limited
    context windows. Different strategies exist, such as fixed token size, sentence splitting,
    or more advanced semantic chunking that tries to keep related ideas together. Overlap between
    chunks helps maintain context across boundaries. This paragraph is intentionally made longer
    to demonstrate how chunking might split it. It keeps going and going, describing the benefits
    of effective text splitting for downstream tasks like summarization, question answering, and
    retrieval-augmented generation (RAG). The goal is to create manageable pieces of text that
    still retain coherence. Semantic chunking often uses embedding models to find natural breakpoints
    in the text's meaning, potentially leading to better results than simple fixed-size chunks.
    The final sentence of this example paragraph.
    """ * 5 # Make it a bit longer for demonstration

    print("Requesting document chunking...")
    # Request chunking using a specific method and size
    chunking_response = await client.tools.chunk_document(
        document=large_document,
        chunk_size=100,     # Target size in tokens (approximate)
        overlap=20,         # Token overlap between consecutive chunks
        method="semantic"   # Options: "token", "sentence", "semantic", "structural" (if available)
    )

    if chunking_response["success"]:
        print(f"Document successfully divided into {chunking_response['chunk_count']} chunks.")
        print(f"Method Used: {chunking_response.get('method_used', 'N/A')}") # Confirm method if returned

        print("\n--- Example Chunks ---")
        for i, chunk in enumerate(chunking_response['chunks'][:3]): # Show first 3 chunks
            print(f"Chunk {i+1} (Length: {len(chunk)} chars):")
            print(f"'{chunk}'\n")
        if chunking_response['chunk_count'] > 3: print("...")
        print("----------------------")

        # These chunks can now be passed individually to other tools (e.g., summarize_document)
    else:
        print(f"Document chunking failed: {chunking_response['error']}")

    await client.close()

# if __name__ == "__main__": asyncio.run(document_chunking_example())
耇数プロバむダヌによるテキスト生成前の䟋ず重耇しおいたすが、構成維持のため蚘茉
import asyncio
from mcp.client import Client

async def multi_provider_completion_example():
    client = Client("http://localhost:8013")
    prompt = "What are the main benefits of using the Model Context Protocol (MCP)?"

    print(f"Requesting completions for prompt: '{prompt}' from multiple providers...")
    multi_response = await client.tools.multi_completion(
        prompt=prompt,
        providers=[
            {"provider": "openai", "model": "gpt-4.1-mini"},
            {"provider": "anthropic", "model": "claude-3-5-haiku-20241022"},
            {"provider": "gemini", "model": "gemini-2.0-flash-lite"}
            # Add more configured providers as needed
        ],
        temperature=0.5,
        max_tokens=250
    )

    if multi_response["success"]:
        print("\n--- Multi-completion Results ---")
        total_cost = multi_response.get("total_cost", 0.0)
        print(f"Total Estimated Cost: ${total_cost:.6f}\n")
        for provider_key, result in multi_response["results"].items():
            print(f"--- Provider: {provider_key} ---")
            if result["success"]:
                print(f"  Model: {result.get('model', 'N/A')}")
                print(f"  Cost: ${result.get('cost', 0.0):.6f}")
                print(f"  Completion:\n{result['completion']}\n")
            else:
                print(f"  Error: {result['error']}\n")
        print("------------------------------")
    else:
        print(f"\nMulti-completion request failed: {multi_response['error']}")

    await client.close()

# if __name__ == "__main__": asyncio.run(multi_provider_completion_example())
構造化デヌタの抜出JSON
import asyncio
from mcp.client import Client
import json

async def json_extraction_example():
    client = Client("http://localhost:8013")
    text_with_data = """
    Meeting Minutes - Project Phoenix - 2024-07-21

    Attendees: Alice (Lead), Bob (Dev), Charlie (QA)
    Date: July 21, 2024
    Project ID: PX-001

    Discussion Points:
    - Reviewed user feedback from v1.1 testing. Mostly positive.
    - Identified performance bottleneck in data processing module. Bob to investigate. Assigned High priority.
    - QA cycle for v1.2 planned to start next Monday (2024-07-29). Charlie confirmed readiness.

    Action Items:
    1. Bob: Investigate performance issue. Due: 2024-07-26. Priority: High. Status: Open.
    2. Alice: Prepare v1.2 release notes. Due: 2024-07-28. Priority: Medium. Status: Open.
    """

    # Define the desired JSON structure (schema)
    desired_schema = {
        "type": "object",
        "properties": {
            "project_name": {"type": "string", "description": "Name of the project"},
            "meeting_date": {"type": "string", "format": "date", "description": "Date of the meeting"},
            "attendees": {"type": "array", "items": {"type": "string"}, "description": "List of attendee names"},
            "action_items": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "task": {"type": "string"},
                        "assigned_to": {"type": "string"},
                        "due_date": {"type": "string", "format": "date"},
                        "priority": {"type": "string", "enum": ["Low", "Medium", "High"]},
                        "status": {"type": "string", "enum": ["Open", "In Progress", "Done"]}
                    },
                    "required": ["task", "assigned_to", "due_date", "priority", "status"]
                }
            }
        },
        "required": ["project_name", "meeting_date", "attendees", "action_items"]
    }

    print("Requesting JSON extraction based on schema...")
    # Request extraction using a model capable of following JSON schema instructions
    json_response = await client.tools.extract_json(
        document=text_with_data,
        json_schema=desired_schema,
        provider="openai", # OpenAI models are generally good at this
        model="gpt-4o", # Use a capable model like GPT-4o or Claude 3.5 Sonnet
        # provider_preference="quality" # Could also use preference
    )

    if json_response["success"]:
        print("JSON extraction successful.")
        print(f"Estimated Cost: ${json_response.get('cost', 0.0):.6f}")

        # The extracted data should conform to the schema
        extracted_json_data = json_response.get('json_data')
        print("\n--- Extracted JSON Data ---")
        # Pretty print the JSON
        print(json.dumps(extracted_json_data, indent=2))
        print("---------------------------")

        # Optionally, validate the output against the schema client-side (requires jsonschema library)
        # try:
        #     from jsonschema import validate
        #     validate(instance=extracted_json_data, schema=desired_schema)
        #     print("\nClient-side validation successful: Output matches schema.")
        # except ImportError:
        #     print("\n(Install jsonschema to perform client-side validation)")
        # except Exception as e:
        #     print(f"\nClient-side validation failed: {e}")

    else:
        print(f"JSON Extraction Error: {json_response.get('error', 'Unknown error')}")
        if 'details' in json_response: print(f"Details: {json_response['details']}")

    await client.close()

# if __name__ == "__main__": asyncio.run(json_extraction_example())
怜玢拡匵生成RAGク゚リ
import asyncio
from mcp.client import Client

async def rag_query_example():
    # This example assumes the Ultimate MCP Server has been configured with a RAG pipeline,
    # including a vector store/index containing relevant documents.
    client = Client("http://localhost:8013")
    query = "What are the latest treatment options for mitigating Alzheimer's disease according to recent studies?"

    print(f"Performing RAG query: '{query}'...")
    # Call the RAG tool, which handles retrieval and generation
    rag_response = await client.tools.rag_query( # Assuming the tool name is 'rag_query'
        query=query,
        # Optional parameters to control the RAG process:
        index_name="medical_research_papers", # Specify the index/collection to search
        top_k=3, # Retrieve top 3 most relevant documents/chunks
        # filter={"year": {"$gte": 2023}}, # Example filter (syntax depends on vector store)
        # generation_model={"provider": "anthropic", "model": "claude-3-5-sonnet-20241022"}, # Specify generation model
        # instruction_prompt="Based on the provided context, answer the user's query concisely." # Customize generation prompt
    )

    if rag_response["success"]:
        print("\nRAG query successful.")
        print(f"Estimated Cost: ${rag_response.get('cost', 0.0):.6f}") # Includes retrieval + generation cost

        print("\n--- Generated Answer ---")
        print(rag_response.get('answer', 'No answer generated.'))
        print("------------------------")

        # The response might also include details about the retrieved sources
        retrieved_sources = rag_response.get('sources', [])
        if retrieved_sources:
            print("\n--- Retrieved Sources ---")
            for i, source in enumerate(retrieved_sources):
                print(f"Source {i+1}:")
                print(f"  ID: {source.get('id', 'N/A')}")
                print(f"  Score: {source.get('score', 'N/A'):.4f}")
                # Depending on RAG setup, might include metadata or text snippet
                print(f"  Content Snippet: {source.get('text', '')[:150]}...")
                print("-" * 15)
            print("-----------------------")
        else:
            print("\nNo sources information provided in the response.")

    else:
        print(f"\nRAG Query Error: {rag_response.get('error', 'Unknown error')}")
        if 'details' in rag_response: print(f"Details: {rag_response['details']}")

    await client.close()

# if __name__ == "__main__": asyncio.run(rag_query_example())
融合怜玢キヌワヌドセマンティック怜玢
import asyncio
from mcp.client import Client

async def fused_search_example():
    # This example assumes the server is configured with a hybrid search provider like Marqo.
    client = Client("http://localhost:8013")
    query = "impact of AI on software development productivity and code quality"

    print(f"Performing fused search for: '{query}'...")
    # Call the fused search tool
    fused_search_response = await client.tools.fused_search( # Assuming tool name is 'fused_search'
        query=query,
        # --- Parameters specific to the hybrid search backend (e.g., Marqo) ---
        index_name="tech_articles_index", # Specify the target index
        searchable_attributes=["title", "content"], # Fields to search within
        limit=5, # Number of results to return
        # Tunable weights for keyword vs. semantic relevance (example)
        hybrid_factors={"keyword_weight": 0.4, "semantic_weight": 0.6},
        # Optional filter string (syntax depends on backend)
        filter_string="publication_year >= 2023 AND source_type='journal'"
        # --------------------------------------------------------------------
    )

    if fused_search_response["success"]:
        print("\nFused search successful.")
        results = fused_search_response.get("results", [])
        print(f"Found {len(results)} hits.")

        if results:
            print("\n--- Search Results ---")
            for i, hit in enumerate(results):
                print(f"Result {i+1}:")
                # Fields depend on Marqo index structure and what's returned
                print(f"  ID: {hit.get('_id', 'N/A')}")
                print(f"  Score: {hit.get('_score', 'N/A'):.4f}") # Combined score
                print(f"  Title: {hit.get('title', 'N/A')}")
                print(f"  Content Snippet: {hit.get('content', '')[:150]}...")
                # Print highlight info if available
                highlights = hit.get('_highlights', {})
                if highlights: print(f"  Highlights: {highlights}")
                print("-" * 15)
            print("--------------------")
        else:
            print("No results found matching the criteria.")

    else:
        print(f"\nFused Search Error: {fused_search_response.get('error', 'Unknown error')}")
        if 'details' in fused_search_response: print(f"Details: {fused_search_response['details']}")

    await client.close()

# if __name__ == "__main__": asyncio.run(fused_search_example())
ロヌカルでのテキスト凊理
import asyncio
from mcp.client import Client

async def local_text_processing_example():
    client = Client("http://localhost:8013")
    # Example assumes a tool named 'process_local_text' exists on the server
    # that bundles various non-LLM text operations.
    raw_text = "  This text has   EXTRA whitespace,\n\nmultiple newlines, \t tabs, and needs Case Normalization.  "

    print("Requesting local text processing operations...")
    local_process_response = await client.tools.process_local_text(
        text=raw_text,
        operations=[
            {"action": "trim_whitespace"},       # Remove leading/trailing whitespace
            {"action": "normalize_whitespace"},  # Collapse multiple spaces/tabs to single space
            {"action": "remove_blank_lines"},    # Remove empty lines
            {"action": "lowercase"}              # Convert to lowercase
            # Other potential actions: uppercase, remove_punctuation, normalize_newlines, etc.
        ]
    )

    if local_process_response["success"]:
        print("\nLocal text processing successful.")
        print(f"Original Text:\n'{raw_text}'")
        print(f"\nProcessed Text:\n'{local_process_response['processed_text']}'")
        # Note: This operation should ideally have zero LLM cost.
        print(f"Cost: ${local_process_response.get('cost', 0.0):.6f}")
    else:
        print(f"\nLocal Text Processing Error: {local_process_response['error']}")

    await client.close()

# if __name__ == "__main__": asyncio.run(local_text_processing_example())
ブラりザヌ自動化の䟋導入ず基本操䜜
import asyncio
from mcp.client import Client

async def browser_basic_interaction_example():
    # This example shows fundamental browser actions controlled by an agent
    client = Client("http://localhost:8013")
    print("--- Browser Automation: Basic Interaction ---")

    # 1. Initialize the browser (creates a browser instance on the server)
    print("\nInitializing browser (headless)...")
    # `headless=True` runs without a visible GUI window (common for automation)
    init_response = await client.tools.browser_init(headless=True, browser_type="chromium")
    if not init_response["success"]:
        print(f"Browser initialization failed: {init_response.get('error', 'Unknown error')}")
        await client.close()
        return
    print("Browser initialized successfully.")
    # Might return session ID if needed for subsequent calls, depends on tool design

    # 2. Navigate to a page
    target_url = "https://example.com/"
    print(f"\nNavigating to {target_url}...")
    # `wait_until` controls when navigation is considered complete
    nav_response = await client.tools.browser_navigate(
        url=target_url,
        wait_until="domcontentloaded" # Options: load, domcontentloaded, networkidle, commit
    )
    if nav_response["success"]:
        print(f"Navigation successful.")
        print(f"  Current URL: {nav_response.get('url', 'N/A')}")
        print(f"  Page Title: {nav_response.get('title', 'N/A')}")
        # The 'snapshot' gives the agent context about the page state (accessibility tree)
        # print(f"  Snapshot: {nav_response.get('snapshot', 'N/A')}")
    else:
        print(f"Navigation failed: {nav_response.get('error', 'Unknown error')}")
        # Attempt to close browser even if navigation failed
        await client.tools.browser_close()
        await client.close()
        return

    # 3. Extract text content using a CSS selector
    selector = "h1" # CSS selector for the main heading
    print(f"\nExtracting text from selector '{selector}'...")
    text_response = await client.tools.browser_get_text(selector=selector)
    if text_response["success"]:
        print(f"Extracted text: '{text_response.get('text', 'N/A')}'")
    else:
        print(f"Text extraction failed: {text_response.get('error', 'Unknown error')}")
        # Optionally check text_response['snapshot'] for page state at time of failure

    # 4. Take a screenshot (optional)
    print("\nTaking a screenshot...")
    screenshot_response = await client.tools.browser_screenshot(
        file_path="example_com_screenshot.png", # Path where server saves the file
        full_page=False, # Capture only the viewport
        image_format="png" # png or jpeg
    )
    if screenshot_response["success"]:
        print(f"Screenshot saved successfully on server at: {screenshot_response.get('saved_path', 'N/A')}")
        # Agent might use this path with a filesystem tool to retrieve the image if needed
    else:
         print(f"Screenshot failed: {screenshot_response.get('error', 'Unknown error')}")

    # 5. Close the browser session
    print("\nClosing the browser...")
    close_response = await client.tools.browser_close()
    if close_response["success"]:
        print("Browser closed successfully.")
    else:
        # Log error, but might happen if browser already crashed
        print(f"Browser close failed (might be expected if previous steps failed): {close_response.get('error', 'Unknown error')}")

    print("--- Browser Automation Example Complete ---")
    await client.close()

# if __name__ == "__main__": asyncio.run(browser_basic_interaction_example())

モデルトヌナメントの実行
import asyncio
from mcp.client import Client
import json

async def model_tournament_example():
    client = Client("http://localhost:8013")
    # Define the task and prompt for the tournament
    task_prompt = "Write a Python function that takes a list of integers and returns a new list containing only the even numbers."
    # Optional: Provide ground truth for automated evaluation if the tool supports it
    ground_truth_code = """
def get_even_numbers(numbers):
    \"\"\"Returns a new list containing only the even numbers from the input list.\"\"\"
    return [num for num in numbers if num % 2 == 0]
"""

    print("Setting up and running a model tournament for code generation...")
    # Call the tournament tool
    tournament_response = await client.tools.run_model_tournament(
        task_type="code_generation", # Helps select appropriate evaluation metrics
        prompt=task_prompt,
        # List of models/providers to compete
        competitors=[
            {"provider": "openai", "model": "gpt-4.1-mini", "temperature": 0.2},
            {"provider": "anthropic", "model": "claude-3-5-sonnet-20241022", "temperature": 0.2},
            {"provider": "deepseek", "model": "deepseek-coder", "temperature": 0.2}, # Specialized coder model
            {"provider": "gemini", "model": "gemini-2.0-pro", "temperature": 0.2},
        ],
        # Criteria for evaluating the generated code
        evaluation_criteria=["correctness", "efficiency", "readability", "docstring_quality"],
        # Provide ground truth if available for automated correctness checks
        ground_truth=ground_truth_code,
        # Optional: Specify an LLM to act as the judge for qualitative criteria
        evaluation_model={"provider": "anthropic", "model": "claude-3-5-opus-20240229"}, # Use a powerful model for judging
        num_rounds=1 # Run multiple rounds for stability if needed
    )

    if tournament_response["success"]:
        print("\n--- Model Tournament Results ---")
        print(f"Task Prompt: {task_prompt}")
        print(f"Total Estimated Cost: ${tournament_response.get('total_cost', 0.0):.6f}\n")

        # Display the ranking
        ranking = tournament_response.get("ranking", [])
        if ranking:
            print("Overall Ranking:")
            for i, result in enumerate(ranking):
                provider = result.get('provider', 'N/A')
                model = result.get('model', 'N/A')
                score = result.get('overall_score', 'N/A')
                cost = result.get('cost', 0.0)
                print(f"  {i+1}. {provider}/{model} - Score: {score:.2f}/10 - Cost: ${cost:.6f}")
        else:
            print("No ranking information available.")

        # Display detailed results for each competitor
        detailed_results = tournament_response.get("results", {})
        if detailed_results:
            print("\nDetailed Scores per Competitor:")
            for competitor_key, details in detailed_results.items():
                 print(f"  Competitor: {competitor_key}")
                 print(f"    Generated Code:\n```python\n{details.get('output', 'N/A')}\n```")
                 scores = details.get('scores', {})
                 if scores:
                     for criterion, score_value in scores.items():
                         print(f"    - {criterion}: {score_value}")
                 print("-" * 10)
        print("------------------------------")

    else:
        print(f"\nModel Tournament Failed: {tournament_response.get('error', 'Unknown error')}")
        if 'details' in tournament_response: print(f"Details: {tournament_response['details']}")

    await client.close()

# if __name__ == "__main__": asyncio.run(model_tournament_example())
ツヌル探玢のためのメタツヌル
import asyncio
from mcp.client import Client
import json

async def meta_tools_example():
    client = Client("http://localhost:8013")
    print("--- Meta Tools Example ---")

    # 1. List all available tools
    print("\nFetching list of available tools...")
    # Assumes a tool named 'list_tools' provides this info
    list_tools_response = await client.tools.list_tools(include_schemas=False) # Set True for full schemas

    if list_tools_response["success"]:
        tools = list_tools_response.get("tools", {})
        print(f"Found {len(tools)} available tools:")
        for tool_name, tool_info in tools.items():
            description = tool_info.get('description', 'No description available.')
            print(f"  - {tool_name}: {description[:100]}...") # Print truncated description
    else:
        print(f"Failed to list tools: {list_tools_response.get('error', 'Unknown error')}")

    # 2. Get detailed information about a specific tool
    tool_to_inspect = "extract_json"
    print(f"\nFetching details for tool: '{tool_to_inspect}'...")
    # Assumes a tool like 'get_tool_info' or using list_tools with specific name/schema flag
    tool_info_response = await client.tools.list_tools(tool_names=[tool_to_inspect], include_schemas=True)

    if tool_info_response["success"] and tool_to_inspect in tool_info_response.get("tools", {}):
        tool_details = tool_info_response["tools"][tool_to_inspect]
        print(f"\nDetails for '{tool_to_inspect}':")
        print(f"  Description: {tool_details.get('description', 'N/A')}")
        # Print the parameter schema if available
        schema = tool_details.get('parameters', {}).get('json_schema', {})
        if schema:
            print(f"  Parameter Schema:\n{json.dumps(schema, indent=2)}")
        else:
            print("  Parameter Schema: Not available.")
    else:
        print(f"Failed to get info for tool '{tool_to_inspect}': {tool_info_response.get('error', 'Not found or error')}")

    # 3. Get tool recommendations for a task (if such a meta tool exists)
    task_description = "Read data from a PDF file, extract tables, and save them as CSV."
    print(f"\nGetting tool recommendations for task: '{task_description}'...")
    # Assumes a tool like 'get_tool_recommendations'
    recommendations_response = await client.tools.get_tool_recommendations(
        task=task_description,
        constraints={"priority": "accuracy", "max_cost_per_doc": 0.10} # Example constraints
    )

    if recommendations_response["success"]:
        print("Recommended Tool Workflow:")
        recommendations = recommendations_response.get("recommendations", [])
        if recommendations:
            for i, step in enumerate(recommendations):
                print(f"  Step {i+1}: Tool='{step.get('tool', 'N/A')}' - Reason: {step.get('reason', 'N/A')}")
        else:
            print("  No recommendations provided.")
    else:
         print(f"Failed to get recommendations: {recommendations_response.get('error', 'Unknown error')}")

    print("\n--- Meta Tools Example Complete ---")
    await client.close()

# if __name__ == "__main__": asyncio.run(meta_tools_example())
ロヌカルのコマンドラむンでのテキスト凊理䟋jq
import asyncio
from mcp.client import Client
import json

async def local_cli_tool_example():
    client = Client("http://localhost:8013")
    print("--- Local CLI Tool Example (jq) ---")

    # Example JSON data to be processed by jq
    json_input_data = json.dumps({
        "users": [
            {"id": 1, "name": "Alice", "email": "[email protected]", "status": "active"},
            {"id": 2, "name": "Bob", "email": "[email protected]", "status": "inactive"},
            {"id": 3, "name": "Charlie", "email": "[email protected]", "status": "active"}
        ],
        "metadata": {"timestamp": "2024-07-21T12:00:00Z"}
    })

    # Define the jq filter to apply
    # This filter selects active users and outputs their name and email
    jq_filter = '.users[] | select(.status=="active") | {name: .name, email: .email}'

    print(f"\nRunning jq with filter: '{jq_filter}' on input JSON...")
    # Call the server tool that wraps jq (e.g., 'run_jq')
    jq_result = await client.tools.run_jq(
        args_str=jq_filter, # Pass the filter as arguments (check tool spec how it expects filters)
        input_data=json_input_data, # Provide the JSON string as input
        # Additional options might be available depending on the tool wrapper:
        # e.g., output_format="json_lines" or "compact_json"
    )

    if jq_result["success"]:
        print("jq execution successful.")
        # stdout typically contains the result of the jq filter
        print("\n--- jq Output (stdout) ---")
        print(jq_result.get("stdout", "No output"))
        print("--------------------------")
        # stderr might contain warnings or errors from jq itself
        stderr_output = jq_result.get("stderr")
        if stderr_output:
            print("\n--- jq Stderr ---")
            print(stderr_output)
            print("-----------------")
        # This should have minimal or zero cost as it runs locally on the server
        print(f"\nCost: ${jq_result.get('cost', 0.0):.6f}")
    else:
        print(f"\njq Execution Error: {jq_result.get('error', 'Unknown error')}")
        print(f"Stderr: {jq_result.get('stderr', 'N/A')}")

    print("\n--- Local CLI Tool Example Complete ---")
    await client.close()

# if __name__ == "__main__": asyncio.run(local_cli_tool_example())
動的 API 統合
import asyncio
from mcp.client import Client
import json

async def dynamic_api_example():
    # This example assumes the server has tools like 'register_api', 'list_registered_apis',
    # 'call_dynamic_tool', and 'unregister_api'.
    client = Client("http://localhost:8013")
    print("--- Dynamic API Integration Example ---")

    # 1. Register an external API using its OpenAPI (Swagger) specification URL
    api_name_to_register = "public_cat_facts"
    openapi_spec_url = "https://catfact.ninja/docs/api-docs.json" # Example public API spec
    print(f"\nRegistering API '{api_name_to_register}' from {openapi_spec_url}...")

    register_response = await client.tools.register_api(
        api_name=api_name_to_register,
        openapi_url=openapi_spec_url,
        # Optional: Provide authentication details if needed (e.g., Bearer token, API Key)
        # authentication={"type": "bearer", "token": "your_api_token"},
        # Optional: Set default headers
        # default_headers={"X-Custom-Header": "value"},
        # Optional: Cache settings for API responses (if tool supports it)
        cache_ttl=300 # Cache responses for 5 minutes
    )

    if register_response["success"]:
        print(f"API '{api_name_to_register}' registered successfully.")
        print(f"  Registered {register_response.get('tools_count', 0)} new MCP tools derived from the API.")
        print(f"  Tools Registered: {register_response.get('tools_registered', [])}")
    else:
        print(f"API registration failed: {register_response.get('error', 'Unknown error')}")
        await client.close()
        return

    # 2. List currently registered dynamic APIs
    print("\nListing registered dynamic APIs...")
    list_apis_response = await client.tools.list_registered_apis()
    if list_apis_response["success"]:
        registered_apis = list_apis_response.get("apis", {})
        print(f"Currently registered APIs: {list(registered_apis.keys())}")
        # print(json.dumps(registered_apis, indent=2)) # Print full details
    else:
        print(f"Failed to list registered APIs: {list_apis_response.get('error', 'Unknown error')}")

    # 3. Call a dynamically created tool corresponding to an API endpoint
    # The tool name is typically derived from the API name and endpoint's operationId or path.
    # Check the 'tools_registered' list from step 1 or documentation for the exact name.
    # Let's assume the tool for GET /fact is 'public_cat_facts_getFact'
    dynamic_tool_name = "public_cat_facts_getFact" # Adjust based on actual registered name
    print(f"\nCalling dynamic tool '{dynamic_tool_name}'...")

    call_response = await client.tools.call_dynamic_tool(
        tool_name=dynamic_tool_name,
        # Provide inputs matching the API endpoint's parameters
        inputs={
            # Example query parameter for GET /fact (check API spec)
             "max_length": 100
        }
    )

    if call_response["success"]:
        print("Dynamic tool call successful.")
        # The result usually contains the API's response body and status code
        print(f"  Status Code: {call_response.get('status_code', 'N/A')}")
        print(f"  Response Body:\n{json.dumps(call_response.get('response_body', {}), indent=2)}")
    else:
        print(f"Dynamic tool call failed: {call_response.get('error', 'Unknown error')}")
        print(f"  Status Code: {call_response.get('status_code', 'N/A')}")
        print(f"  Response Body: {call_response.get('response_body', 'N/A')}")

    # 4. Unregister the API when no longer needed (optional cleanup)
    print(f"\nUnregistering API '{api_name_to_register}'...")
    unregister_response = await client.tools.unregister_api(api_name=api_name_to_register)
    if unregister_response["success"]:
        print(f"API unregistered successfully. Removed {unregister_response.get('tools_count', 0)} tools.")
    else:
        print(f"API unregistration failed: {unregister_response.get('error', 'Unknown error')}")

    print("\n--- Dynamic API Integration Example Complete ---")
    await client.close()

# if __name__ == "__main__": asyncio.run(dynamic_api_example())
OCR の䜿甚䟋
import asyncio
from mcp.client import Client
import os

async def ocr_example():
    # Requires 'ocr' extras installed: uv pip install -e ".[ocr]"
    # Also requires Tesseract OCR engine installed on the server host system.
    client = Client("http://localhost:8013")
    print("--- OCR Tool Example ---")

    # --- Create dummy files for testing ---
    # In a real scenario, these files would exist on a path accessible by the server.
    # Ensure the server process has permissions to read these files.
    dummy_files_dir = "ocr_test_files"
    os.makedirs(dummy_files_dir, exist_ok=True)
    dummy_pdf_path = os.path.join(dummy_files_dir, "dummy_document.pdf")
    dummy_image_path = os.path.join(dummy_files_dir, "dummy_image.png")

    # Create a simple dummy PDF (requires reportlab - pip install reportlab)
    try:
        from reportlab.pdfgen import canvas
        from reportlab.lib.pagesizes import letter
        c = canvas.Canvas(dummy_pdf_path, pagesize=letter)
        c.drawString(100, 750, "This is page 1 of a dummy PDF.")
        c.drawString(100, 730, "It contains some text for OCR testing.")
        c.showPage()
        c.drawString(100, 750, "This is page 2.")
        c.save()
        print(f"Created dummy PDF: {dummy_pdf_path}")
    except ImportError:
        print("Could not create dummy PDF: reportlab not installed. Skipping PDF test.")
        dummy_pdf_path = None
    except Exception as e:
        print(f"Error creating dummy PDF: {e}. Skipping PDF test.")
        dummy_pdf_path = None

    # Create a simple dummy PNG image (requires Pillow - pip install Pillow)
    try:
        from PIL import Image, ImageDraw, ImageFont
        img = Image.new('RGB', (400, 100), color = (255, 255, 255))
        d = ImageDraw.Draw(img)
        # Use a default font if possible, otherwise basic text
        try: font = ImageFont.truetype("arial.ttf", 15)
        except IOError: font = ImageFont.load_default()
        d.text((10,10), "Dummy Image Text for OCR\nLine 2 of text.", fill=(0,0,0), font=font)
        img.save(dummy_image_path)
        print(f"Created dummy Image: {dummy_image_path}")
    except ImportError:
        print("Could not create dummy Image: Pillow not installed. Skipping Image test.")
        dummy_image_path = None
    except Exception as e:
        print(f"Error creating dummy Image: {e}. Skipping Image test.")
        dummy_image_path = None
    # --- End of dummy file creation ---


    # 1. Extract text from the PDF using OCR and LLM correction
    if dummy_pdf_path:
        print(f"\nExtracting text from PDF: {dummy_pdf_path} (using hybrid method)...")
        pdf_text_result = await client.tools.extract_text_from_pdf(
            file_path=dummy_pdf_path, # Server needs access to this path
            extraction_method="hybrid", # Try direct extraction, fallback to OCR
            max_pages=2, # Limit pages to process
            reformat_as_markdown=True, # Request markdown formatting
            # Optional: Use an LLM to correct/improve the raw OCR text
            llm_correction_model={"provider": "openai", "model": "gpt-4.1-mini"}
        )
        if pdf_text_result["success"]:
            print("PDF text extraction successful.")
            print(f"  Method Used: {pdf_text_result.get('extraction_method_used', 'N/A')}")
            print(f"  Cost (incl. LLM correction): ${pdf_text_result.get('cost', 0.0):.6f}")
            print("\n--- Extracted PDF Text (Markdown) ---")
            print(pdf_text_result.get("text", "No text extracted."))
            print("-------------------------------------")
        else:
            print(f"PDF OCR failed: {pdf_text_result.get('error', 'Unknown error')}")
            if 'details' in pdf_text_result: print(f"Details: {pdf_text_result['details']}")
    else:
         print("\nSkipping PDF OCR test as dummy file could not be created.")


    # 2. Process the image file with OCR and preprocessing
    if dummy_image_path:
        print(f"\nProcessing image OCR: {dummy_image_path} with preprocessing...")
        image_text_result = await client.tools.process_image_ocr(
            image_path=dummy_image_path, # Server needs access to this path
            # Optional preprocessing steps (require OpenCV on server)
            preprocessing_options={
                "grayscale": True,
                # "threshold": "otsu", # e.g., otsu, adaptive
                # "denoise": True,
                # "deskew": True
            },
            ocr_language="eng" # Specify language(s) for Tesseract e.g., "eng+fra"
            # Optional LLM enhancement for image OCR results
            # llm_enhancement_model={"provider": "gemini", "model": "gemini-2.0-flash-lite"}
        )
        if image_text_result["success"]:
            print("Image OCR successful.")
            print(f"  Cost (incl. LLM enhancement): ${image_text_result.get('cost', 0.0):.6f}")
            print("\n--- Extracted Image Text ---")
            print(image_text_result.get("text", "No text extracted."))
            print("----------------------------")
        else:
            print(f"Image OCR failed: {image_text_result.get('error', 'Unknown error')}")
            if 'details' in image_text_result: print(f"Details: {image_text_result['details']}")
    else:
         print("\nSkipping Image OCR test as dummy file could not be created.")

    # --- Clean up dummy files ---
    # try:
    #     if dummy_pdf_path and os.path.exists(dummy_pdf_path): os.remove(dummy_pdf_path)
    #     if dummy_image_path and os.path.exists(dummy_image_path): os.remove(dummy_image_path)
    #     if os.path.exists(dummy_files_dir): os.rmdir(dummy_files_dir) # Only if empty
    # except Exception as e:
    #      print(f"\nError cleaning up dummy files: {e}")
    # --- End cleanup ---

    print("\n--- OCR Tool Example Complete ---")
    await client.close()

# if __name__ == "__main__": asyncio.run(ocr_example())

(泚ファむルパスを䜿甚する倚くの䟋では、サヌバヌプロセスがそれらのパスにアクセスできるこずを前提ずしおいたす。Docker でデプロむする堎合、通垞はボリュヌムのマッピングが必芁です。)


✹ 自埋型ドキュメントリファむナヌ

Ultimate MCP Server には、登録枈みの MCP ツヌルのドキュメントを自埋的に分析、テスト、改善する匷力な機胜が含たれおいたす。ultimate/tools/docstring_refiner.py に実装されたこの機胜は、Claude のような倧芏暡蚀語モデルLLMがツヌルを呌び出す際の䜿いやすさず信頌性の向䞊に圹立ちたす。

仕組み

ドキュメントリファむナヌは、䜓系的か぀反埩的なアプロヌチに埓いたす。

  1. ゚ヌゞェントのシミュレヌションLLM ゚ヌゞェントが珟圚のドキュメントdocstring、スキヌマ、䜿甚䟋をどのように解釈するかをシミュレヌションし、正しく呌び出すために重芁な曖昧さや䞍足情報を特定したす。
  2. 適応型テスト生成ツヌルの入力スキヌマパラメヌタヌの型、制玄、必須フィヌルド、シミュレヌション結果、以前の改善サむクルで発生した倱敗に基づき、倚様なテストケヌスを䜜成したす。十分なカバレッゞを目指したす。
  3. スキヌマを考慮したテスト生成したテスト入力を、実行する前にツヌルのスキヌマず照合しお怜蚌したす。有効なテストは、サヌバヌ環境内で実際のツヌル実装に察しお実行したす。
  4. アンサンブルによる倱敗分析テストに倱敗した堎合出力が誀っおいる、゚ラヌが発生するなど、耇数の LLM が、そのテスト実行に䜿甚された特定バヌゞョンのドキュメントを螏たえお倱敗を分析し、ドキュメントの匱点を特定したす。
  5. 構造化された改善案分析に基づき、システムは具䜓的で的を絞った改善案を生成したす。
    • 説明衚珟を倉曎したり、明確な説明を远加したりしたす。
    • スキヌマJSON Patch 操䜜による倉曎を提案したすパラメヌタヌぞの説明の远加、型の調敎、䜿甚䟋の远加など。
    • 䜿甚䟋新しい䜿甚䟋を生成するか、既存の䜿甚䟋を改善したす。
  6. 怜蚌枈みのスキヌマパッチ適甚提案された JSON パッチをスキヌマにメモリ䞊で適甚し、次の反埩に向けお倉曎を受け入れる前に、倉曎埌のスキヌマ構造を怜蚌したす。
  7. 反埩的な改善テストに安定しお合栌するか、最倧反埩回数に達するたで、テスト生成 → 実行 → 倱敗分析 → 改善案の提瀺 → スキヌマぞのパッチ適甚、ずいうサむクルを繰り返したす。
  8. 任意の刈り蟌み反埩の埌、テストで刀明した重芁な情報を維持しながら、ドキュメントを簡朔にたずめお敎える最終確認を行いたす。
メリット
  • 手䜜業の削枛LLM が利甚する高品質なツヌルドキュメントの䜜成ず保守に䌎う、煩雑になりがちな䜜業を自動化したす。
  • ゚ヌゞェントの性胜向䞊より明確で粟床の高いドキュメントを䜜成し、LLM がツヌルを䜿う際の゚ラヌを枛らしたす。
  • ゚ッゞケヌスの特定テストプロセスによっお、人間の䜜成者が芋萜ずす可胜性のある曖昧さや゚ッゞケヌスを発芋できたす。
  • 䞀貫性の向䞊すべおのツヌルのドキュメントで、より統䞀されたスタむルず詳现床を確立できたす。
  • フィヌドバックぞの適応シミュレヌションした゚ヌゞェントの倱敗から盎接孊習し、ドキュメントの特定の匱点に察凊したす。
  • スキヌマの進化䜿甚シミュレヌションに基づき、怜蚌を経ながらツヌルスキヌマを段階的に改善できたす。
  • 詳现なレポヌト実行したテスト、発生した倱敗、行った倉曎など、改善プロセス党䜓の包括的なログずレポヌトを提䟛したす。
制限事項ず考慮点
  • コストず時間ツヌルごず、反埩ごずに、シミュレヌション、テスト生成、倱敗分析、改善案の提瀺に耇数回の LLM 呌び出しが必芁ずなるため、蚈算コストが高く、時間もかかる堎合がありたす。
  • リ゜ヌスの消費特に、倚数のツヌルを改善する堎合や、分析に倧芏暡な LLM を䜿甚する堎合は、かなりの CPUメモリが必芁になるこずがありたす。
  • LLM ぞの䟝存改善の品質は、分析ず生成の工皋で䜿甚する LLM の胜力に倧きく巊右されたす。
  • スキヌマの耇雑さ非垞に耇雑なスキヌマや入れ子構造のスキヌマに察しお、正しく意味のある JSON Patch を生成するこずは、LLM にずっお難しい堎合がありたす。
  • 決定性このプロセスでは LLM を䜿甚するため、実行ごずに結果が完党には再珟されない可胜性がありたす。
  • 保守の耇雑さリファむナヌ自䜓が耇雑なシステムであり、䟝存関係の保守が必芁です。
䜿甚するタむミング

この機胜は、特に次のような堎合に圹立ちたす。

  • LLM ゚ヌゞェントに公開しおいる MCP ツヌルの数が倚い堎合。
  • ゚ヌゞェントによるドキュメントの誀解が原因ず思われるツヌルの䜿甚倱敗が頻繁に発生しおいる堎合。
  • ツヌル゚コシステムを積極的に開発たたは拡匵しおおり、䞀貫性のある高品質なドキュメントを確保する必芁がある堎合。
  • 基盀ずなるツヌルのコヌドを必ずしも倉曎せずに、゚ヌゞェントの信頌性ずパフォヌマンスを事前に向䞊させたい堎合。
  • この自動品質改善プロセスに投資する予算LLM クレゞットず時間がある堎合。
䜿甚䟋サヌバヌ偎からの呌び出し

ドキュメント改善ツヌルは通垞、サヌバヌ偎の保守たたは管理タスクずしお呌び出され、倖郚゚ヌゞェントが呌び出す MCP ツヌルずしお盎接公開されるこずはありたせん。

# This code snippet shows how the refiner might be called from within the
# server's environment (e.g., via a CLI command or admin interface).

# Assume necessary imports and context setup:
# from ultimate_mcp_server.tools.docstring_refiner import refine_tool_documentation
# from ultimate_mcp_server.core import mcp_context # Represents the server's context

async def invoke_doc_refiner_task():
    # Ensure mcp_context is properly initialized with registered tools, config, etc.
    print("Starting Autonomous Documentation Refinement Task...")

    # Example: Refine documentation for a specific list of tools
    refinement_result = await refine_tool_documentation(
        tool_names=["extract_json", "browser_navigate", "chunk_document"], # Tools to refine
        max_iterations=3, # Limit refinement cycles per tool
        refinement_model_config={ # Specify LLM for refinement tasks
            "provider": "anthropic",
            "model": "claude-3-5-sonnet-20241022"
        },
        testing_model_config={ # Optional: Specify LLM for test generation/simulation
            "provider": "openai",
            "model": "gpt-4o"
        },
        enable_winnowing=True, # Apply final streamlining pass
        stop_on_first_error=False, # Continue refining other tools if one fails
        ctx=mcp_context # Pass the server's MCP context
    )

    # Example: Refine all available tools (potentially very long running)
    # refinement_result = await refine_tool_documentation(
    #     refine_all_available=True,
    #     max_iterations=2,
    #     ctx=mcp_context
    # )

    print("\nDocumentation Refinement Task Complete.")

    # Process the results
    if refinement_result["success"]:
        print(f"Successfully processed {len(refinement_result.get('refined_tools', []))} tools.")
        # The actual docstrings/schemas of the tools in mcp_context might be updated in-memory.
        # Persisting these changes would require additional logic (e.g., writing back to source files).
        print("Detailed report available in the result object.")
        # print(refinement_result.get('report')) # Contains detailed logs and changes
    else:
        print(f"Refinement task encountered errors: {refinement_result.get('error', 'Unknown error')}")
        # Check the report for details on which tools failed and why.

# To run this, it would need to be integrated into the server's startup sequence,
# a dedicated CLI command, or an administrative task runner.
# e.g., await invoke_doc_refiner_task()

✅ サンプルラむブラリずテストフレヌムワヌク

Ultimate MCP Server には、examples/ ディレクトリに 35 件を超える゚ンドツヌ゚ンドのサンプルが甚意されおいたす。これらは次の 2 ぀の目的を果たしたす。

  1. 生きたドキュメントほがすべおのツヌルず機胜に぀いお、実甚的で珟実的な䜿甚パタヌンを瀺したす。
  2. 統合テストスむヌトすべおのコンポヌネントが正しく連携するこずを確認する、包括的なテストスむヌトを構成したす。
サンプルの構成ず敎理
  • 機胜別サンプルは機胜ごずに分類されおいたす䟋model_integration、tool_specific、workflows、advanced_features。
  • 単䜓で実行可胜各サンプル*.pyは、mcp-client を䜿っお実行䞭のサヌバヌむンスタンスずやり取りする、実行可胜な Python スクリプトです。
  • わかりやすい出力Rich ラむブラリを䜿い、リク゚スト、レスポンス、コスト、所芁時間、結果を明確に瀺す、曞匏蚭定ず色分けを斜したコン゜ヌル出力を行いたす。
  • ゚ラヌ凊理堅牢なデモを実珟するため、サンプルには基本的な゚ラヌチェックが含たれおいたす。
芋やすい出力

次のような、情報が充実したコン゜ヌル出力を確認できたす。

  • 📊 結果ず統蚈をたずめたテヌブル。
  • 🎚 コヌドず JSON のシンタックスハむラむト。
  • ⏳ 進捗むンゞケヌタヌたたは詳现なステップログ。
  • 🖌 出力セクションを敎理するパネル。

出力䟋

╭────────────────────── Tournament Results ───────────────────────╮
│ [1] claude-3-5-haiku-20241022: Score 8.7/10                    │
│     Cost: $0.00013                                             │
│ ...                                                            │
╰────────────────────────────────────────────────────────────────╯
カスタマむズず孊習
  • カスタマむズ可胜.env 経由で API キヌを䜿甚したり、別のモデル、カスタムプロンプト、入力ファむルを䜿甚したりするよう、サンプルを簡単に倉曎できたす。
  • コマンドラむン匕数倚くのサンプルはカスタマむズ甚の匕数を受け付けたす䟋--model、--input-file、--headless。
  • 孊習に圹立぀内容AI アプリケヌションの構成、ツヌルの遞択、パラメヌタヌの調敎、゚ラヌ凊理、コストの最適化、統合パタヌンに関するベストプラクティスを孊べたす。
包括的なテストフレヌムワヌク

run_all_demo_scripts_and_check_for_errors.py スクリプトは、すべおのサンプルをテストスむヌトずしお実行したす。

  • 自動実行examples/*.py を怜出し、順番に実行したす。
  • 怜蚌終了コヌドず stderr を事前定矩されたパタヌンず照合し、実際の゚ラヌず想定内のメッセヌゞ䟋API キヌがないこずを瀺す譊告を区別したす。
  • レポヌト成功、倱敗、スキップしたテストの抂芁ず、詳现なログを含むサマリヌレポヌトを生成したす。

テストフレヌムワヌクの蚭定䟋

"sql_database_interactions_demo.py": {
    "expected_exit_code": 0,
    "allowed_stderr_patterns": [
        r"Could not compute statistics...", # Known non-fatal warning
        r"Connection failed...", # Expected if DB not set up
        r"Configuration not yet loaded..." # Standard info message
    ]
}
サンプルスむヌトの実行
# Ensure the Ultimate MCP Server is running in a separate terminal

# Run the entire test suite
python run_all_demo_scripts_and_check_for_errors.py

# Run a specific example script directly
python examples/browser_automation_demo.py --headless

# Run an example with custom arguments
python examples/text_redline_demo.py --input-file1 path/to/doc1.txt --input-file2 path/to/doc2.txt

このサンプルラむブラリずテストフレヌムワヌクの組み合わせは、Ultimate MCP Server の機胜を理解し、掻甚し、怜蚌するための非垞に貎重なリ゜ヌスです。


💻 CLI コマンド

Ultimate MCP Server には、サヌバヌ管理ずツヌルずのやり取りに䜿甚できるコマンドラむンむンタヌフェむスumcpが甚意されおいたす。

# Show available commands and global options
umcp --help

# --- Server Management ---
# Start the server (loads .env, registers tools)
umcp run [--host HOST] [--port PORT] [--include-tools tool1 tool2] [--exclude-tools tool3 tool4]

# --- Information ---
# List configured LLM providers
umcp providers [--check] [--models]

# List available tools
umcp tools [--category CATEGORY] [--examples]

# --- Testing & Interaction ---
# Test connection and basic generation for a specific provider
umcp test <provider_name> [--model MODEL_NAME] [--prompt TEXT]

# Generate a completion directly from the CLI
umcp complete --provider <provider_name> --model <model_name> --prompt "Your prompt here" [--temperature N] [--max-tokens N] [--system TEXT] [--stream]

# --- Cache Management ---
# View or clear the request cache
umcp cache [--status] [--clear]

# --- Benchmark ---
umcp benchmark [--providers P1 P2] [--models M1 M2] [--prompt TEXT] [--runs N]

# --- Examples ---
umcp examples [--list] [<example_name>] [--category CATEGORY]

各コマンドには通垞、远加のオプションがありたす。特定のコマンドのオプションを確認するには、umcp COMMAND --help を䜿甚したす䟋umcp complete --help。


🛠 高床な蚭定

蚭定は䞻に環境倉数で管理され、倚くの堎合、起動時にプロゞェクトルヌトの .env ファむルから読み蟌たれたす。

サヌバヌ蚭定
  • SERVER_HOSTデフォルト127.0.0.1バむンドするネットワヌクむンタヌフェヌスです。すべおのむンタヌフェヌスで埅ち受けるには、0.0.0.0 を䜿甚したすDocker コンテナや倖郚からのアクセスに必芁です。
  • SERVER_PORTデフォルト8013サヌバヌが埅ち受けるポヌトです。
  • API_PREFIXデフォルト/すべおの API ゚ンドポむントの URL プレフィックスです䟋/mcp/v1 に蚭定するず、そのパス配䞋で提䟛されたす。
  • WORKERS任意。䟋4Web サヌバヌ䟋Uvicornのワヌカヌプロセス数です。CPU コア数に応じお調敎しおください。
ツヌルのフィルタリング起動時の制埡

CLI フラグを䜿甚しお、サヌバヌ起動時に登録するツヌルを制埡できたす。

  • --include-tools tool1,tool2,...指定したツヌルのみを登録したす。
  • --exclude-tools tool3,tool4,...指定したツヌルを陀くすべおのツヌルを登録したす。
    # 䟋ファむルシステムず基本的な補完ツヌルのみで起動
    umcp run --include-tools read_file,write_file,list_directory,completion
    # 䟋ブラりザヌ操䜜以倖のすべおのツヌルで起動
    umcp run --exclude-tools browser_init,browser_navigate,browser_click
    
    軜量なむンスタンスの䜜成、䟝存関係の管理、゚ヌゞェントの機胜制限に圹立ちたす。
ロギング蚭定
  • LOG_LEVELデフォルトINFOログの詳现床DEBUG、INFO、WARNING、ERROR、CRITICALを制埡したす。DEBUG は非垞に詳现です。
  • USE_RICH_LOGGINGデフォルトtrueRich ラむブラリを䜿甚しお、色付きの構造化されたコン゜ヌルログを有効にしたす。プレヌンテキストのログを䜿甚する堎合ファむルぞのリダむレクトや䞀郚のロギングシステムでの䜿甚に適しおいたすは、false に蚭定したす。
  • LOG_FORMAT任意カスタムのログ圢匏を指定する Python logging 曞匏文字列ですUSE_RICH_LOGGING=false の堎合。
  • LOG_TO_FILE任意。䟋/var/log/ultimate_mcp_server.logコン゜ヌルに加えおログを曞き蟌むファむルのパスです。サヌバヌプロセスに曞き蟌み暩限があるこずを確認しおください。
キャッシュ蚭定
  • CACHE_ENABLEDデフォルトtrue応答キャッシュをグロヌバルに有効たたは無効にしたす。
  • CACHE_TTLデフォルト86400 秒24 時間キャッシュ項目のデフォルトの有効期間です。ツヌルによっおは個別に䞊曞きされる堎合がありたす。
  • CACHE_TYPEデフォルトmemoryバック゚ンドストレヌゞです。察応する皮類䟋memory、redis、diskcacheに぀いおは、実装を確認しおください。diskcache は氞続化に察応しおいたす。
  • CACHE_DIRデフォルト./.cacheCACHE_TYPE=diskcache の堎合に䜿甚するディレクトリです。曞き蟌み暩限があるこずを確認しおください。
  • CACHE_MAX_SIZE任意。䟋diskcache の項目数の堎合は 1000、512MB の堎合は 536870912キャッシュのサむズ制限を蚭定したす。
  • REDIS_URLCACHE_TYPE=redis の堎合は必須Redis サヌバヌぞの接続 URL です䟋redis://localhost:6379/0。
プロバむダヌのタむムアりトず再詊行
  • PROVIDER_TIMEOUTデフォルト120LLM プロバむダヌ API からの応答を埅぀際のデフォルトのタむムアりト時間秒です。
  • PROVIDER_MAX_RETRIESデフォルト3プロバむダヌぞのリク゚ストが倱敗した堎合のデフォルトの再詊行回数ですレヌト制限や䞀時的なサヌバヌの問題など、再詊行可胜な゚ラヌが察象です。指数バックオフを䜿甚したす。
  • 専甚の倉数䟋OPENAI_TIMEOUT、ANTHROPIC_MAX_RETRIESで、プロバむダヌごずに個別の蚭定を䞊曞きできる堎合がありたす。蚭定の読み蟌み凊理たたはドキュメントを確認しおください。
ツヌル固有の蚭定

個々のツヌルは、環境倉数から独自の蚭定を読み蟌む堎合がありたす。䟋

  • ALLOWED_DIRSファむルシステムツヌルがアクセスを蚱可されるベヌスディレクトリのカンマ区切りリストです。セキュリティ䞊、特に重芁です。
  • PLAYWRIGHT_BROWSER_TYPEデフォルトchromiumPlaywright ツヌルが䜿甚するブラりザヌですchromium、firefox、webkit。
  • PLAYWRIGHT_TIMEOUTPlaywright の操䜜に察するデフォルトのタむムアりトです。
  • DATABASE_URLSQL デヌタベヌス連携ツヌル甚の接続文字列ですSQLAlchemy を䜿甚。
  • MARQO_URL統合怜玢ツヌルが䜿甚する Marqo むンスタンスの URL です。
  • TESSERACT_CMDTesseract の実行ファむルがシステムの暙準 PATH にない堎合のパスですOCR 甚。

サヌバヌを起動する前に、環境倉数が正しく蚭定されおいるこずを必ず確認しおください。倉曎を反映するには、通垞サヌバヌの再起動が必芁です。


☁ デプロむに関する考慮事項

開発には umcp run や docker compose up で十分ですが、より堅牢なデプロむでは次の方法を怜蚎しおください。

1. バックグラりンドサヌビスずしお実行する

サヌバヌが継続しお皌働し、自動的に再起動するようにしおください。

  • systemdLinux サヌビスナニットファむル.serviceを䜜成し、systemctl start|stop|restart|status でプロセスを管理したす。堅牢な制埡機胜ずログ連携を提䟛したす。
  • supervisor Python で蚘述されたプロセス制埡システムです。supervisord を蚭定しお、サヌバヌプロセスを監芖および管理したす。
  • Docker の再起動ポリシヌ docker run コマンドたたは docker-compose.yml で --restart unless-stopped たたは --restart always を䜿甚し、Docker が再起動を管理するようにしたす。
2. リバヌスプロキシを䜿甚するNginx、Caddy、Apache、Traefik

Ultimate MCP Server の前段にリバヌスプロキシを配眮するこずを匷く掚奚したす

  • 🔒 HTTPS/SSL 終端 SSL 蚌明曞䟋CaddyCertbot を䜿甚した Let's Encryptを凊理し、倖郚トラフィックを暗号化したす。
  • ⚖ ロヌドバランシング 高可甚性やスケヌリングのために耇数のサヌバヌむンスタンスを実行しおいる堎合、トラフィックを分散したす。
  • 🗺 パスルヌティング わかりやすい倖郚 URL䟋https://api.yourdomain.com/mcp/を内郚サヌバヌhttp://localhost:8013にマッピングしたす。必芁に応じお API_PREFIX を蚭定したす。
  • 🛡 セキュリティヘッダヌ Strict-Transport-SecurityHSTSや Content-Security-PolicyCSPなどの重芁なヘッダヌを远加したす。
  • 🚊 アクセス制埡 IP 蚱可リストや基本認蚌を実装するか、OAuth2 プロキシず連携したす。
  • ⏳ バッファリングキャッシュ リク゚ストレスポンスのバッファリングやキャッシュ局を远加で提䟛する堎合がありたす。
  • ⏱ タむムアりト アプリケヌションサヌバヌずは独立しお、接続タむムアりトを管理したす。

Nginx の location ブロックの䟋簡略版

location /mcp/ { # Match your desired public path (corresponds to API_PREFIX if set)
    proxy_pass http://127.0.0.1:8013/; # Point to the internal server (note trailing /)
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;

    # Increase timeouts for potentially long-running AI tasks
    proxy_connect_timeout 60s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;

    # Optional: Add basic authentication
    # auth_basic "Restricted Access";
    # auth_basic_user_file /etc/nginx/.htpasswd;
}
3. コンテナオヌケストレヌションKubernetes、Docker Swarm

スケヌラブルで管理されたデプロむには、次の方法を怜蚎しおください

  • ❀ ヘルスチェック デプロむメントマニフェストで、サヌバヌの /healthz ゚ンドポむントたたは同等のものを䜿甚するラむブネスプロヌブずレディネスプロヌブを実装しお蚭定したす。
  • 🔑 蚭定 環境倉数や API キヌは、むメヌゞに組み蟌んだり .env ファむルだけに䟝存したりせず、ConfigMaps ず SecretsKubernetesたたは Docker SecretsConfigs を䜿甚しお安党に管理したす。
  • ⚙ リ゜ヌス制限 安定したパフォヌマンスを確保し、ノヌド䞊のリ゜ヌス䞍足を避けるため、コンテナに適切な CPU ずメモリのリク゚スト制限を定矩したす。
  • 🌐 サヌビスディスカバリヌ IP アドレスやホスト名をハヌドコヌドする代わりに、オヌケストレヌタヌに組み蟌たれたサヌビスディスカバリヌを利甚したす。サヌビスを内郚向けに公開し䟋ClusterIP、倖郚からのアクセスには Ingress コントロヌラヌを䜿甚したす。
  • 💟 氞続ストレヌゞ 氞続性が必芁な機胜䟋diskcache、氞続メモリ、ファむルストレヌゞを䜿甚する堎合は、氞続ボリュヌムPVs/PVCsを蚭定したす。
4. リ゜ヌスの割り圓お
  • RAM 特に倧芏暡なモデルの䜿甚、メモリ内キャッシュ、サむズの倧きいドキュメントの凊理、たたはメモリを倧量に消費するツヌルブラりザヌ自動化や特定のデヌタ凊理タスクなどの実行時には、十分なメモリを確保しおください。䜿甚量を監芖しおください。
  • CPU CPU 負荷を監芖しおください。LLM の掚論自䜓は CPU に負荷が集䞭しない堎合がありたす倚くの堎合、GPUTPU を䜿甚したすが、ほかのツヌルOCR、ロヌカル凊理、リク゚ストを凊理するりェブサヌバヌなどは CPU に負荷をかけるこずがありたす。ワヌカヌ数WORKERS 環境倉数を怜蚎しおください。
  • ディスク I/O 氞続キャッシュdiskcacheや倧芏暡なファむルシステム操䜜を利甚する堎合、ボトルネックになるこずがありたす。必芁に応じお高速なストレヌゞSSDを䜿甚しおください。
  • ネットワヌク 特にサむズの倧きいドキュメントや画像を扱う堎合、たたは倧容量の API 応答を頻繁に凊理する堎合は、十分な垯域幅を確保しおください。

💞 委任によるコスト削枛

Ultimate MCP Server を䜿甚しおむンテリゞェントな委任を行うず、すべおのタスクに Claude 3.7 Sonnet や GPT-4o のような高性胜モデルだけを䜿甚する堎合ず比べお、倧幅なコスト削枛が期埅できたす。

タスクのシナリオ高性胜モデルのみ抂算MCP Server 経由で委任抂算掚定削枛率備考
100 ペヌゞのドキュメントを芁玄~$4.50 - $6.00~$0.45 - $0.70 (Gemini Flash)~90%分割䜎コストの芁玄を䞊列実行
50 件のレコヌドからデヌタを抜出~$2.25 - $3.00~$0.35 - $0.50 (GPT-4.1 Mini)~84%コスト効率の高いモデルによるバッチ凊理
コンテンツのアむデアを 20 件生成~$0.90 - $1.20~$0.12 - $0.20 (DeepSeek/Haiku)~87%䜎コストモデルによるシンプルな生成タスク
顧客からの問い合わせを 1,000 件凊理~$45.00 - $60.00~$7.50 - $12.00 (Mixed Models)~83%問い合わせの耇雑さに応じたルヌティング
10 件のスキャン画像を OCR 凊理しお抜出~$1.50 - $2.50 (If LLM OCR)~$0.20 - $0.40 (OCR + LLM Fix)~85%専甚 OCR䜎コスト LLM による修正
基本的なりェブスクレむピングず芁玄~$0.50 - $1.00~$0.10 - $0.20 (Browser + Haiku)~80%ブラりザヌツヌル䜎コスト LLM による芁玄

(コストはあくたで参考倀であり、䞀般的なトヌクン数ず 2024 幎の抂算䟡栌に基づいおいたす。実際のコストは、ドキュメントのサむズや耇雑さ、䜿甚するモデル、各プロバむダヌの珟圚の料金に倧きく巊右されたす。)

コスト削枛の方法

  • タスクに合ったモデルの遞択 深い掚論、創造性、たたは耇雑な指瀺ぞの察応が必芁なタスクに限り、高䟡なモデルを䜿甚したす。
  • 䜎コストモデルの掻甚 芁玄、抜出、シンプルな Q&A、曞匏蚭定などを、Gemini Flash、Claude Haiku、GPT-4.1 Mini、DeepSeek Chat のような倧幅に䜎コストなモデルに委任したす。
  • 専甚ツヌルの利甚 適切な堎合は、LLM 以倖のツヌルファむルシステム、OCR、ブラりザヌ、CLI ナヌティリティ、デヌタベヌスを䜿甚し、それらの操䜜では LLM API の呌び出しを完党に避けたす。
  • キャッシュ 同䞀たたは意味的に類䌌したリク゚ストに察する重耇した API 呌び出しを枛らしたす。

Ultimate MCP Server はむンテリゞェントなルヌティングレむダヌずしお機胜し、高床な゚ヌゞェントアヌキテクチャ内でこうしたコスト最適化を実珟したす。


🧠 AI 間の委任が重芁な理由

Ultimate MCP Server のようなシステムによっお実珟される AI 間の委任は、単玔なコスト削枛にずどたらない戊略的な重芁性を持ちたす。

高床な AI 機胜の民䞻化
  • Claude 3.7 や GPT-4o のような最先端の掚論モデルに日垞的な䜜業を任せるこずで、その胜力をより幅広い甚途で実際に利甚できるようにしたす。
  • 予算に制玄のある組織でも、党䜓のコストを効果的に管理しながら、重芁な掚論の段階で最高氎準の AI 機胜を掻甚できるようにしたす。
  • 業界党䜓で AI リ゜ヌスをより効率的か぀広範に掻甚できるようにしたす。
経枈的なリ゜ヌス最適化
  • AI の利甚における基本的な経枈的最適化を実珟したす。最も高䟡なリ゜ヌス最䞊䜍クラスの LLM 掚論は、その独自の䟡倀が必芁な堎面に限っお適甚したす。
  • 耇雑な掚論、創造性、埮劙なニュアンスの理解、オヌケストレヌションは、高性胜モデルに任せたす。
  • 定型的なデヌタ凊理、抜出、フォヌマット倉換、より単玔な質疑応答は、費甚察効果の高いモデルで凊理したす。
  • 特化型の非 LLM タスクりェブスクレむピング、ファむル I/O、DB ク゚リは、専甚ツヌルで凊理し、䞍芁な LLM 呌び出しを回避したす。
  • システム党䜓ずしお、混合コストを倧幅に抑えながら、最䞊䜍クラスに近い性胜ず胜力の実珟を目指したす。
  • むンテリゞェントなルヌティングずキャッシュにより、予枬が難しい LLM API コストを、より管理しやすい支出ぞず倉えたす。
持続可胜な AI アヌキテクチャ
  • すべおのタスクで最倧芏暡のモデルを䜿うこずに䌎う蚈算負荷を軜枛し、より持続可胜な AI の利甚を促進したす。
  • AI リ゜ヌスの割り圓おに、胜力に応じた階局型のアプロヌチを導入したす。
  • 倚くの反埩で安䟡なモデルやツヌルを利甚できるため、より倧芏暡な実隓ず開発が可胜になりたす。
  • コストが制埡䞍胜なほど膚らむこずなく、ビゞネスのニヌズに合わせお拡匵できる AI 統合のアプロヌチを提䟛したす。
技術的な進化の道筋
  • 単䞀モデルぞのモノリシックな呌び出しから、分散型のマルチ゚ヌゞェント、マルチモデルのワヌクフロヌぞず移行する、AI アプリケヌションアヌキテクチャの重芁な進化を瀺したす。
  • 倚様なツヌルやモデルを組み合わせた耇雑な凊理パむプラむンの、高床で AI 駆動型のオヌケストレヌションを可胜にしたす。
  • AI システムが自身のリ゜ヌス䜿甚に぀いお掚論し、動的に最適化できる可胜性を持぀、システムの基盀を築きたす。
  • コンテキスト、コスト、求められる品質に基づいおむンテリゞェントな委任を刀断できる、より自埋的で自己最適化する AI システムの実珟に぀なげたす。
AI 効率化の未来
  • Ultimate MCP Server は、AI システムが自らの運甚コストずリ゜ヌス䜿甚を積極的に管理、最適化する未来を瀺しおいたす。
  • 高性胜モデルは、特化型ツヌルや費甚察効果の高い「ワヌカヌ」モデルの゚コシステムを支える、むンテリゞェントなオヌケストレヌタヌ、぀たり「マネヌゞャヌ」ずしお機胜したす。
  • AI ワヌクフロヌはたすたす高床化し、自己組織化やレゞリ゚ンスを備える可胜性がありたす。
  • 組織は、基本的な凊理から高床な掚論たで、AI の胜力党䜓を、財務的に実行可胜か぀拡匵性のある方法で掻甚できたす。

効率的で、むンテリゞェントな委任を行い、自己最適化する AI システムずいうこの構想は、実甚的な AI 導入における次のフロンティアを瀺しおいたす。ほがすべおの甚途で単䞀の匷力か぀高䟡なモデルを䜿うこずが倚い珟圚のパラダむムを超えるものです。


🧱 アヌキテクチャ

MCP 統合の仕組み

Ultimate MCP Server は、Model Context ProtocolMCPをネむティブに実装しおいたす。

  1. MCP サヌバヌのコアMCP 仕様に準拠した受信 HTTP リク゚スト通垞は特定の゚ンドポむントぞの POST リク゚ストを埅ち受ける Web サヌバヌFastAPI などを䜿甚を実装したす。
  2. ツヌルの登録起動時に、サヌバヌは利甚可胜なすべおのツヌル実装を怜出しお登録したす。各ツヌルは、名前、説明、入出力スキヌマ倚くの堎合、Pydantic モデルを JSON Schema に倉換したものなどのメタデヌタを提䟛したす。このレゞストリにより、サヌバヌおよび堎合によっおぱヌゞェントは、どのツヌルを利甚できるか、たたその䜿い方を把握できたす。
  3. ツヌルの呌び出しMCP クラむアントClaude や別のアプリケヌションなどが、ツヌル名ずパラメヌタヌを指定した有効な MCP リク゚ストを送信するず、サヌバヌのコアがリク゚ストを適切な登録枈みツヌルの実行ロゞックに振り分けたす。
  4. コンテキストの受け枡しず実行ツヌルは怜蚌枈みの入力パラメヌタヌを受け取りたす。ツヌルはアクションLLM の呌び出し、Playwright ずの連携、DB ぞのク゚リ、ファむルの操䜜などを実行したす。
  5. 構造化されたレスポンスツヌルの実行結果たたぱラヌは、暙準的な MCP レスポンス圢匏にたずめられたす。通垞、この圢匏にはステヌタス成功倱敗、出力デヌタツヌルの出力スキヌマに準拠、コスト情報、その他のメタデヌタが含たれたす。
  6. クラむアントぞの返华MCP サヌバヌのコアは、構造化された MCP レスポンスを HTTP 経由でリク゚スト元のクラむアントに返したす。

MCP 暙準に準拠するこずで、MCP 察応のあらゆる゚ヌゞェントやクラむアントアプリケヌションず、シヌムレスか぀予枬可胜に統合できたす。

コンポヌネント図
+---------------------+       MCP Request        +------------------------------------+       API Request       +-----------------+
|   MCP Agent/Client  | ----------------------> |        Ultimate MCP Server         | ----------------------> |  LLM Providers  |
| (e.g., Claude 3.7)  | <---------------------- | (FastAPI + MCP Core + Tool Logic)  | <---------------------- | (OpenAI, Anthro.)|
+---------------------+      MCP Response       +------------------+-----------------+      API Response       +--------+--------+
                                                            |                                       |
                                                            | Tool Invocation                       | External API Call
                                                            ▌                                       ▌
+-----------------------------------------------------------+------------------------------------------------------------+
| Internal Services & Tool Implementations                                                                               |
| +-------------------+  +-------------------+  +-------------------+  +-------------------+  +-------------------+       |
| | Completion/LLM    |  | Document Proc.    |  | Data Extraction   |  | Browser Automation|  | Excel Automation  |       |
| | (Routing/Provider)|  | (Chunking, Sum.)  |  | (JSON, Table)     |  | (Playwright)      |  | (OpenPyXL/COM)    |       |
| +---------+---------+  +-------------------+  +-------------------+  +-------------------+  +-------------------+       |
|           |                                                                                                            |
| +---------+---------+  +-------------------+  +-------------------+  +-------------------+  +-------------------+       |
| | Cognitive Memory  |  | Filesystem Ops    |  | SQL Database      |  | Entity/Graph      |  | Vector/RAG        |       |
| | (Storage/Query)   |  | (Secure Access)   |  | (SQLAlchemy)      |  | (NetworkX)        |  | (Vector Stores)   |       |
| +-------------------+  +-------------------+  +-------------------+  +-------------------+  +---------+---------+       |
|                                                                                                        |                 |
| +-------------------+  +-------------------+  +-------------------+  +-------------------+  +---------+---------+       |
| | Audio Transcription|  | OCR Tools         |  | Text Classify     |  | CLI Tools         |  | Dynamic API       |       |
| | (Whisper, etc.)   |  | (Tesseract+LLM)   |  |                   |  | (jq, rg, awk)     |  | (OpenAPI->Tool)   |       |
| +-------------------+  +-------------------+  +-------------------+  +-------------------+  +-------------------+       |
|                                                                                                                        |
| +-------------------+  +-------------------+  +-------------------+  +-------------------+  +-------------------+       |
| | Caching Service   |  | Analytics/Metrics |  | Prompt Management |  | Config Service    |  | Meta Tools/Refiner|       |
| | (Memory/Disk/Redis|  | (Cost/Usage Track)|  | (Jinja2/Repo)     |  | (Loads .env)      |  | (list_tools etc.) |       |
| +-------------------+  +-------------------+  +-------------------+  +-------------------+  +-------------------+       |
+------------------------------------------------------------------------------------------------------------------------+
委譲のリク゚ストフロヌ詳现
  1. ゚ヌゞェントの刀断MCP ゚ヌゞェントは、委譲に適しおいる可胜性のある特定の機胜倧きなテキストの芁玄、JSON の抜出、URL の閲芧などが必芁だず刀断したす。
  2. MCP リク゚ストの䜜成゚ヌゞェントは、ツヌルのスキヌマlist_tools を䜿っお事前に取埗しおいる堎合がありたすに埓っお tool_name ず必須の inputs を指定し、MCP ツヌル呌び出しリク゚ストを䜜成したす。
  3. サヌバヌぞの HTTP POST゚ヌゞェントは、このリク゚スト通垞は本文に JSON ずしお栌玍を HTTP POST で Ultimate MCP Server の指定゚ンドポむントに送信したす。
  4. リク゚ストの受信ず解析サヌバヌの Web フレヌムワヌクFastAPIがリク゚ストを受信したす。MCP Core は JSON 本文を解析し、䞀般的な MCP リク゚スト構造に照らしお怜蚌したす。
  5. ツヌルの振り分けMCP Core は、登録枈みツヌルのレゞストリから、リク゚ストされた tool_name を怜玢したす。
  6. 入力の怜蚌サヌバヌは、リク゚ストで指定された inputs を、該圓ツヌル固有の入力スキヌマPydantic モデルに照らしお怜蚌したす。怜蚌に倱敗した堎合は、盎ちに MCP ゚ラヌレスポンスが生成されたす。
  7. ツヌル実行コンテキスト蚭定や、共有サヌビスロギング、キャッシュ、分析などぞのアクセスを含むコンテキストオブゞェクトが䜜成されるこずがありたす。
  8. キャッシュの確認キャッシュサヌビスを参照したす。tool_name ず怜蚌枈みの inputs に基づいおキャッシュキヌを生成したす。このキヌに察応する有効期限内のキャッシュ゚ントリヌが存圚する堎合、キャッシュされたレスポンスを取埗しお返し、手順 14 に進みたす。
  9. ツヌルロゞックの実行キャッシュされおいない堎合、ツヌルの䞻な実行ロゞックが動䜜したす。
    • LLM タスクツヌルが LLM の呌び出しを䌎う堎合completion、summarize_document、extract_json など
      • 最適化ルヌティングロゞックが、パラメヌタヌprovider、model、provider_preferenceずサヌバヌ蚭定に基づいおプロバむダヌモデルを遞択したす。
      • プロンプト管理サヌビスが、テンプレヌトを䜿っお最終的なプロンプトを敎えるこずがありたす。
      • プロバむダヌ抜象化レむダヌが、遞択したプロバむダヌ向けの API リク゚ストを䜜成したす。
      • API が呌び出され、必芁に応じお再詊行やタむムアりトが凊理されたす。
      • LLM の応答を受信し、解析したす。
    • 専甚ツヌルタスクLLM を䜿わないツヌルread_file、browser_navigate、run_sql_query、run_ripgrep などの堎合
      • ツヌルは、関連するシステムファむルシステム、Playwright のブラりザヌむンスタンス、デヌタベヌス接続、サブプロセスの実行などず盎接やり取りしたす。
      • セキュリティチェック蚱可されたディレクトリ、SQL サニタむズ甚プレヌスホルダヌなどが実行されたす。
      • 操䜜の結果が取埗されたす。
  10. コストの蚈算LLM タスクでは、分析サヌビスが入出力トヌクン数ずプロバむダヌの料金に基づいお掚定コストを蚈算したす。それ以倖のタスクでは、特定の蚈量察象リ゜ヌスを消費しない限り、通垞コストはれロです。
  11. 結果のフォヌマットツヌルは、定矩枈みの出力スキヌマに埓っお、結果デヌタたたぱラヌメッセヌゞをフォヌマットしたす。
  12. 分析デヌタの蚘録分析サヌビスは、リク゚スト、レスポンスたたぱラヌ、実行時間、コスト、䜿甚したプロバむダヌモデル、キャッシュの状態ヒットミスなどを蚘録したす。
  13. キャッシュの曎新操䜜が成功し、このツヌルリク゚ストでキャッシュが有効になっおいる堎合、キャッシュサヌビスは蚈算された TTL を蚭定しお、フォヌマット枈みのレスポンスを保存したす。
  14. MCP レスポンスの䜜成MCP Core は、最終結果キャッシュから取埗したもの、たたは実行結果を暙準の MCP レスポンス構造に栌玍したす。この構造には status、outputs、errorある堎合、さらに cost や usage_metadata が含たれるこずがありたす。
  15. ゚ヌゞェントぞの HTTP レスポンスサヌバヌは、MCP レスポンスを HTTP レスポンスずしお゚ヌゞェントに返したす通垞は、ツヌルの操䜜が倱敗した堎合でもステヌタスは 200 OK です。MCP リク゚スト自䜓は成功しおいるためです。゚ヌゞェントはこのレスポンスを解析し、ツヌル呌び出しの結果を刀断したす。

🌍 実際のナヌスケヌス

高床な AI ゚ヌゞェント機胜

Claude のような゚ヌゞェントや独自に構築した自埋型゚ヌゞェントにツヌルを提䟛するこずで、耇雑なマルチモヌダルタスクを実行できるようにしたす。

  • 氞続メモリず孊習 Cognitive Memory システムを䜿甚しお、長時間の䌚話やタスクを通じおコンテキストを維持したす。
  • りェブ操䜜ず調査 りェブ閲芧、りェブサむトからのデヌタ抜出、フォヌム送信を自動化し、耇数のオンラむン゜ヌスから情報を統合したす。
  • デヌタ分析ずレポヌト䜜成 Excel スプレッドシヌト内のデヌタを䜜成、操䜜、分析し、グラフやレポヌトを生成したす。
  • デヌタベヌス操䜜 ゚ヌゞェントの目暙に基づいお情報を取埗たたは曎新するために、䌁業デヌタベヌスにアクセスしおク゚リを実行したす。
  • ドキュメント理解 PDF や画像OCRを凊理し、重芁な情報を抜出し、長いレポヌトを芁玄し、ドキュメントに基づく質問に回答したすRAG。
  • ナレッゞグラフ管理 特定の分野、プロゞェクト、たたぱンティティに関する瀟内ナレッゞグラフを構築し、ク゚リを実行したす。
  • マルチメディア凊理 䌚議の録音や音声メモを文字起こししたす。
  • コヌド実行ず分析 開発やデヌタタスクに CLI ツヌルたたは専甚のコヌドツヌル远加した堎合を䜿甚したす。
  • 倖郚サヌビス連携 OpenAPI 経由で動的に登録された他瀟の API やパブリック API ずやり取りしたす。
゚ンタヌプラむズワヌクフロヌの自動化

AI 掚論ず専甚ツヌルを掻甚する、高床な自動プロセスを構築したす。

  • むンテリゞェントなドキュメント凊理パむプラむン スキャン文曞PDF を取り蟌み -> OCR -> 構造化デヌタJSONを抜出 -> デヌタを怜蚌 -> ドキュメントの皮類を分類 -> 適切なシステムに振り分けるか、人による確認甚に芁玄したす。
  • 自動調査アシスタント トピックを指定 -> 孊術デヌタベヌスを怜玢Browser/API ツヌル経由 -> 関連する論文をダりンロヌドBrowser/Filesystem -> 論文を分割しお芁玄ドキュメントツヌル -> 重芁な知芋を抜出抜出ツヌル -> Cognitive Memory に保存 -> 情報を統合したレポヌトを生成したす。
  • 財務レポヌトの自動化 デヌタベヌスに接続SQL ツヌル -> 財務デヌタを抜出 -> Excel テンプレヌトに入力Excel ツヌル -> グラフず差異分析を生成 -> レポヌトをメヌルで送信メヌルツヌルを远加した堎合。
  • カスタマヌサポヌトチケットの情報拡充 チケットのテキストを受信 -> 問題の皮類を分類分類ツヌル -> 瀟内ナレッゞベヌスずドキュメントを怜玢RAG ツヌル -> 返信案を䜜成 -> CRM から顧客情報を远加DB たたは API ツヌル経由。
  • 競合他瀟のモニタリング ブラりザヌ自動化タスクをスケゞュヌル -> 競合他瀟のりェブサむトニュヌスフィヌドを閲芧 -> 重芁な発衚や䟡栌倉曎を抜出 -> 調査結果を芁玄 -> 関連チヌムに通知したす。
デヌタ凊理ず連携

単玔な ETL にずどたらない耇雑なデヌタタスクを凊理したす。

  • 非構造化デヌタから構造化デヌタぞ メヌル、レポヌト、チャットログ、補品レビュヌから特定の情報JSON、テヌブルを抜出したす。
  • ナレッゞグラフの䜜成 ドキュメントコヌパス䟋瀟内 Wiki、研究論文を凊理し、知芋を怜玢するための゚ンティティ関係グラフを構築したす。
  • デヌタ倉換ずクレンゞング LLM の指瀺に基づく耇雑なデヌタ操䜜に、SQL ツヌル、Excel の自動化、たたはロヌカルのテキスト凊理awk、sedを䜿甚したす。
  • デヌタの自動分類 テキスト分類ツヌルを倧芏暡なデヌタセット䟋ナヌザヌフィヌドバックの分類、ニュヌス蚘事ぞのタグ付けに適甚したす。
  • セマンティックデヌタ怜玢 瀟内ドキュメントに察しお怜玢可胜なベクトルむンデックスを構築し、ナヌザヌや゚ヌゞェントがキヌワヌドだけでなく意味に基づいお情報を怜玢できるようにしたすRAG。
研究ず分析科孊、マヌケットなど

AI を掻甚したツヌルで研究チヌムを支揎したす。

  • 文献の自動怜玢ずレビュヌ ブラりザヌAPI ツヌルを䜿甚しおデヌタベヌスPubMed、ArXiv などを怜玢し、論文をダりンロヌド、分割、芁玄しお、䞻芁な方法論や結果を抜出したす。
  • 比范分析 耇数プロバむダヌの補完ツヌルやトヌナメントツヌルを䜿甚しお、研究デヌタに基づく仮説の解釈や生成の方法をモデル間で比范したす。
  • 研究からのデヌタ抜出 公開論文やレポヌトから構造化デヌタ参加者数、p 倀、結果を自動的に抜出し、デヌタベヌスやスプレッドシヌトに取り蟌みたす。
  • 予算の远跡 分析機胜を掻甚しお、研究タスクに䌎う LLM API のコストを監芖したす。
  • 研究ログの継続的な蚘録 Cognitive Memory システムを䜿甚しお、研究プロゞェクト党䜓を通じお知芋、仮説、芳察、掚論の手順を保存したす。
ドキュメントむンテリゞェンス

ドキュメントコレクションを理解するための包括的なシステムを構築したす。

  • ゚ンドツヌ゚ンドのパむプラむン スキャンしたドキュメントを OCR で凊理 -> LLM でテキストを匷化 -> 定矩枈みのフィヌルドを抜出Extraction ツヌル -> ドキュメントの皮類を分類 -> 䞻芁な゚ンティティ関係を特定 -> 芁玄を生成 -> テキストずメタデヌタを怜玢可胜なシステムVectorSQL DBにむンデックス化したす。
財務分析ずモデリング

高床なツヌルを財務の専門家に提䟛したす。

  • AI を掻甚したモデル構築 自然蚀語で Excel 自動化ツヌルに指瀺し、耇雑な財務モデル、予枬、評䟡分析を䜜成したす。
  • デヌタ統合 ブラりザヌ自動化や API を介しお垂堎デヌタを取埗し、デヌタベヌスSQL ツヌルからの瀟内デヌタず組み合わせたす。
  • レポヌト分析 RAG たたは芁玄ツヌルを䜿甚しお、長い財務レポヌトや開瀺曞類の内容をすばやく把握したす。
  • シナリオテスト Excel モデルの入力倀をプログラムで倉曎しお、感床分析を実行したす。
  • 意思決定の蚘録 Cognitive Memory を䜿甚しお、投資刀断や分析の根拠を蚘録したす。

🔐 セキュリティに関する考慮事項

Ultimate MCP Server のデプロむず運甚では、セキュリティを最優先事項ずする必芁がありたす。以䞋の点を考慮しおください。

  1. 🔑 API キヌの管理

    • ゜ヌスコヌドに API キヌをハヌドコヌドしたり、バヌゞョン管理にコミットしたりしないでください。
    • 環境倉数ロヌカル開発では .env ファむル、システムの環境倉数、本番環境では HashiCorp Vault、AWS Secrets Manager、GCP Secret Manager などのシヌクレット管理ツヌルを掚奚を䜿甚しおください。
    • .env ファむルをロヌカルで䜿甚する堎合は、厳栌なファむル暩限䟋chmod 600 .envを蚭定し、サヌバヌを実行するナヌザヌだけが読み取れるようにしおください。
    • 開発環境ず本番環境では 別々のキヌ を䜿甚しおください。
    • キヌのロヌテヌションポリシヌを実斜し、挏えいの疑いがあるキヌは盎ちに無効化しおください。
  2. 🌐 ネットワヌクの公開ずアクセス制埡

    • ロヌカル接続のみを蚱可するため、デフォルトでは 127.0.0.1SERVER_HOSTにバむンドしおください。公開する意図がある堎合に限り 0.0.0.0 に倉曎し、必ず適切なネットワヌク制埡の背埌に配眮しおください。
    • リバヌスプロキシを䜿甚しおください サヌバヌの前段に Nginx、Caddy、Traefik などを配眮するこずを匷く掚奚したす。SSL/TLS の終端凊理を行い、アクセス制埡IP 蚱可リスト、クラむアント蚌明曞認蚌、Basic Auth、OAuth2 プロキシ連携を適甚できるほか、分離レむダヌを提䟛したす。
    • ファむアりォヌルルヌル ホストベヌスたたはネットワヌクファむアりォヌルを蚭定し、信頌できる送信元リバヌスプロキシの IP、特定のアプリケヌションサヌバヌの IP、VPN の範囲などからのみ SERVER_PORT にアクセスできるように制限しおください。
  3. 👀 認蚌ず認可

    • Ultimate MCP Server 自䜓には、ナヌザヌ゚ヌゞェント認蚌機胜が組み蟌たれおいない堎合がありたす。認蚌は通垞、サヌバヌより前段のレむダヌリバヌスプロキシや API ゲヌトりェむなどで凊理しおください。
    • 認可されたクラむアント信頌できる AI ゚ヌゞェントや特定のバック゚ンドサヌビスのみが、サヌバヌ゚ンドポむントにリク゚ストを送信できるようにしおください。必芁に応じお、盞互 TLSmTLSや、プロキシゲヌトりェむで管理する API キヌトヌクンの䜿甚を怜蚎しおください。
    • ツヌルによっおアクセスレベルが異なる堎合読み取り専甚ず読み曞き可胜なファむルシステムなど、認可ロゞックをサヌバヌ内で凊理する必芁があるか、倖郚で管理するかを怜蚎しおください。
  4. 🚊 レヌト制限ず䞍正利甚の防止

    • リバヌスプロキシたたは API ゲヌトりェむのレベルで、送信元 IP、API キヌ、その他の識別情報に基づくレヌト制限を実装しおください。これにより、サヌビス拒吊DoS攻撃を防ぎ、過剰な API 䜿甚LLM およびツヌルの䜿甚にかかる費甚を含むのコスト管理にも圹立ちたす。
    • 䞍正利甚の兆候がないか、䜿甚パタヌンを監芖しおください。
  5. 🛡 入力の怜蚌ずサニタむズ

    • MCP は構造化された圢匏を提䟛したすが、ナヌザヌ゚ヌゞェントの入力に基づいお倖郚システムず連携するツヌルには、特に泚意しおください。
      • ファむルシステムツヌル 最も重芁なのは、ALLOWED_DIRS を厳密に蚭定するこずです。ディレクトリトラバヌサル../を防ぐため、すべおのパス入力を厳栌に怜蚌し、正芏化しおください。サヌバヌプロセスは最小暩限で実行しおください。
      • SQL ツヌル SQL むンゞェクションの脆匱性を防ぐため、パラメヌタヌ化ク゚リたたは ORMSQLAlchemy などを適切に䜿甚しおください。゚ヌゞェントの入力から SQL 文字列を盎接構築するのは避けおください。
      • ブラりザヌツヌル 任意の JavaScriptbrowser_evaluate_scriptを実行するツヌルには泚意しおください。可胜であれば、信頌できない゚ヌゞェントの入力に盎接基づくスクリプトの実行は避けおください。Playwright のサンドボックス機胜は圹立ちたすが、䞇党ではありたせん。
      • CLI ツヌル コマンドむンゞェクションを防ぐため、run_ripgrep、run_jq などのツヌルに枡す匕数をサニタむズしおください。特に、耇雑なコマンド文字列を構築する堎合は泚意が必芁です。入力デヌタの受け枡しには、安党な方法䟋暙準入力を䜿甚しおください。
    • すべおのツヌル入力に぀いお、Pydantic スキヌマを䜿甚しお入力デヌタの型ず制玄を怜蚌しおください。
  6. 📊 䟝存関係のセキュリティ

    • サヌドパヌティラむブラリFastAPI、Pydantic、Playwright、デヌタベヌスドラむバヌなどの既知の脆匱性にパッチを適甚するため、uv pip install --upgrade ... たたは uv sync を䜿甚しお、䟝存関係を定期的に曎新しおください。
    • セキュリティスキャンツヌルpip-audit、GitHub Dependabot、Snykを䜿甚しお、pyproject.toml たたは requirements.txt 内の脆匱な䟝存関係を自動的に特定しおください。
  7. 📄 ログのセキュリティ

    • DEBUG レベルのログには、プロンプト党文、API レスポンス、ファむルの内容、デヌタに含たれるキヌなどの機密情報が蚘録される堎合がありたす。本番環境では、LOG_LEVEL を適切に蚭定しおください通垞、INFO たたは WARNING の方が安党です。
    • ログファむルLOG_TO_FILE を䜿甚する堎合に適切なアクセス蚱可が蚭定されおいるこずを確認し、ログロヌテヌションず保持ポリシヌも怜蚎しおください。API キヌをそのたたログに蚘録するのは避けおください。
  8. ⚙ ツヌル固有のセキュリティ

    • 有効にしおいる各ツヌル固有のセキュリティ䞊の圱響を確認しおください。ファむルの曞き蟌みやコヌドの実行、デヌタベヌスぞのアクセスが可胜なツヌルはありたすか蚭定ALLOWED_DIRS や、暩限を制限したデヌタベヌス認蚌情報などが最小暩限の原則に埓っおいるこずを確認しおください。䞍芁なツヌルや、環境に合わせお十分に安党にできないツヌルは無効にしおください。

📃 ラむセンス

このプロゞェクトは MIT LicenseOpenAI/Anthropic Rider を含むの䞋でラむセンスされおいたす。詳现は LICENSE ファむルをご芧ください。


🙏 謝蟞

このプロゞェクトは、数倚くの玠晎らしいオヌプン゜ヌスプロゞェクトやサヌビスの成果を基盀ずしおいたす。特に、以䞋の方々に感謝したす。

  • 基盀ずなる抂念ずプロトコル仕様を提䟛しおくださった Model Context Protocol (MCP)。
  • 高性胜なりェブフレヌムワヌクを提䟛しおくださった FastAPI チヌム。
  • 堅牢なデヌタ怜蚌ず蚭定管理を実珟しおくださった Pydantic の開発者の皆様。
  • 矎しく分かりやすいタヌミナル出力を実珟しおくださった Rich ラむブラリ。
  • 非垞に高速な Python パッケヌゞのむンストヌルず䟝存関係の解決を提䟛しおくださった Astral の uv。
  • 匷力なブラりザヌ自動化フレヌムワヌクを提䟛しおくださった Microsoft の Playwright チヌム。
  • Excel ファむル操䜜を可胜にしおくださった OpenPyXL のメンテナヌの皆様。
  • デヌタベヌスツヌルキットを開発しおくださった SQLAlchemy の開発者の皆様。
  • Tesseract、ripgrep、jq、awk、sed など、統合されたツヌルの開発者の皆様。
  • 匷力なモデルを API 経由で利甚できるようにしおくださった、すべおの LLM プロバむダヌOpenAI、Anthropic、Google、DeepSeek、xAI など。
  • Python およびオヌプン゜ヌスのコミュニティ党䜓。

この README では、党䜓像を詳しく説明しおいたす。個別のツヌルのパラメヌタヌ、高床な蚭定オプション、実装に関する詳现な説明に぀いおは、プロゞェクト内の゜ヌスコヌドず各ツヌルのドキュメントを参照しおください。

サヌバヌの実行

CLI を䜿甚しおサヌバヌを起動したす。

# Start in default stdio mode
umcp run

# Start in streamable-http mode for web interfaces or remote clients (recommended)
umcp run --transport-mode shttp
# Or use the shortcut:
umcp run -t shttp

# Run on a specific host and port (streamable-http mode)
umcp run -t shttp --host 0.0.0.0 --port 8080

コメント

MCP は初めおですか

プロトコルの抂芁から最初のサヌバヌの導入たで、よくある疑問にたずめお答えたす。

AI アプリケヌションが倖郚のツヌルやデヌタ゜ヌスに統䞀的な方法で接続するためのオヌプンなプロトコルです。クラむアントはモデルずの察話を担い、MCP サヌバヌはツヌル・リ゜ヌス・プロンプトテンプレヌトを提䟛したす。暙準メッセヌゞでやり取りするため、1 ぀のサヌバヌを耇数のクラむアントで再利甚できたす。