# 2-2 三大核心機制:Tools、Resources、Prompts 回到白皮書首頁:[MCP 全方位技術白皮書](/@thc1006/mcp-whitepaper-home) --- ## MCP 的三位一體:工具、資源、提示的完美協作 如果把 MCP 比作一個智慧工廠,那麼 **Tools(工具)** 就是生產線上的機器設備,**Resources(資源)** 就是原料倉庫,而 **Prompts(提示)** 則是作業指導書。這三個核心機制相互配合,讓 AI 能夠像熟練的工程師一樣,知道用什麼工具、取什麼材料、按什麼步驟來完成複雜的任務。 ## Tools(工具):AI 的動手能力 ### 工具的本質:可執行的功能單元 Tools 是 MCP 中最「主動」的組件,它們是 AI 可以調用的具體功能,能夠執行實際的操作和計算。 **工具的特徵:** - **動作導向**:執行具體的操作(讀取、寫入、計算、調用 API) - **參數化**:接受輸入參數,產生輸出結果 - **狀態改變**:可能會修改外部系統的狀態 - **即時執行**:被調用時立即執行 ### 工具定義與發現機制 **標準工具定義格式:** ```json { "name": "analyze_sales_data", "title": "銷售數據分析工具", "description": "分析特定時間範圍內的銷售數據,生成趨勢報告", "inputSchema": { "type": "object", "properties": { "start_date": { "type": "string", "format": "date", "description": "分析開始日期 (YYYY-MM-DD)" }, "end_date": { "type": "string", "format": "date", "description": "分析結束日期 (YYYY-MM-DD)" }, "region": { "type": "string", "enum": ["north", "south", "central", "all"], "description": "分析區域" }, "metrics": { "type": "array", "items": { "type": "string", "enum": ["revenue", "units", "growth", "forecast"] }, "description": "要分析的指標" } }, "required": ["start_date", "end_date"] } } ``` **工具發現流程:** ```python class SalesAnalyticsMCPServer: def __init__(self): self.tools = self._register_tools() def _register_tools(self): """註冊所有可用工具""" return { "analyze_sales_data": self._analyze_sales_data, "generate_forecast": self._generate_forecast, "compare_periods": self._compare_periods, "export_report": self._export_report } async def list_tools(self): """回應工具列表請求""" return [ { "name": "analyze_sales_data", "description": "分析銷售數據並生成報告", "inputSchema": {...} # 完整的 JSON Schema }, # ... 其他工具 ] async def call_tool(self, name: str, arguments: dict): """執行特定工具""" if name not in self.tools: raise ToolNotFoundError(f"Tool '{name}' not found") return await self.tools[name](**arguments) ``` ### 工具的執行模式 **1. 同步執行(適合快速操作)** ```python async def get_customer_info(self, customer_id: str) -> dict: """同步獲取客戶資訊""" customer = await self.db.query( "SELECT * FROM customers WHERE id = ?", customer_id ) return { "customer_id": customer.id, "name": customer.name, "email": customer.email, "status": customer.status } ``` **2. 異步執行(適合長時間操作)** ```python async def generate_annual_report(self, year: int) -> dict: """異步生成年度報告""" task_id = str(uuid.uuid4()) # 啟動背景任務 asyncio.create_task(self._background_report_generation(task_id, year)) return { "task_id": task_id, "status": "processing", "estimated_completion": "15-20 minutes", "progress_endpoint": f"/tasks/{task_id}/progress" } ``` **3. 流式執行(適合即時回饋)** ```python async def stream_log_analysis(self, log_file: str): """流式分析日誌檔案""" async for line in self._read_log_file(log_file): analysis_result = await self._analyze_line(line) yield { "line_number": line.number, "timestamp": line.timestamp, "severity": analysis_result.severity, "message": analysis_result.message } ``` ## Resources(資源):AI 的知識庫 ### 資源的定義:上下文提供者 Resources 是 MCP 中的「被動」組件,它們提供 AI 需要的背景資訊和上下文數據,但不執行動作。 **資源的特徵:** - **資訊導向**:提供數據、文件、配置等資訊 - **唯讀性質**:通常只能讀取,不能修改 - **上下文豐富**:為 AI 決策提供背景知識 - **結構化數據**:以標準格式提供資訊 ### 資源的 URI 系統 MCP 使用 URI 來唯一標識資源,支援各種類型的數據來源: **檔案系統資源:** ``` file:///home/user/documents/product_catalog.pdf file:///etc/nginx/nginx.conf file:///var/log/application.log ``` **資料庫資源:** ``` postgres://localhost:5432/sales/customers mongodb://cluster.example.com/inventory/products redis://cache.example.com/session/user_123 ``` **API 資源:** ``` api://weather.example.com/current/taipei api://stock.example.com/quotes/2330.TW api://news.example.com/tech/latest ``` **自定義資源:** ``` screen://localhost/display1 sensor://factory/temperature/line_a config://app/database/connection_string ``` ### 資源實現範例 **配置資源:** ```python class ConfigurationResource: def __init__(self, config_path: str): self.config_path = config_path async def get_resource(self, uri: str) -> Resource: """獲取配置資源""" if uri == "config://app/database": config = await self._load_config(self.config_path) return Resource( uri=uri, name="Database Configuration", description="應用程式資料庫配置", mimeType="application/json", text=json.dumps(config.database, indent=2) ) ``` **動態資源:** ```python class SystemMetricsResource: async def get_resource(self, uri: str) -> Resource: """獲取系統指標""" if uri == "metrics://system/current": metrics = { "cpu_usage": psutil.cpu_percent(), "memory_usage": psutil.virtual_memory().percent, "disk_usage": psutil.disk_usage('/').percent, "load_average": os.getloadavg(), "timestamp": datetime.now().isoformat() } return Resource( uri=uri, name="Current System Metrics", description="即時系統效能指標", mimeType="application/json", text=json.dumps(metrics, indent=2) ) ``` ### 資源的智能選擇 **上下文感知的資源推薦:** ```python class IntelligentResourceManager: def __init__(self): self.resource_index = {} self.usage_patterns = {} def recommend_resources(self, task_context: str, user_context: dict) -> List[str]: """基於任務和用戶上下文推薦相關資源""" # 分析任務需求 task_keywords = self._extract_keywords(task_context) # 找出相關資源 relevant_resources = [] for resource_uri, metadata in self.resource_index.items(): if self._calculate_relevance(task_keywords, metadata) > 0.7: relevant_resources.append(resource_uri) # 根據用戶歷史使用模式排序 return self._rank_by_user_preference(relevant_resources, user_context) ``` ## Prompts(提示):AI 的作業指導書 ### 提示的作用:標準化 AI 行為 Prompts 是預定義的指令模板,用來引導 AI 以一致和有效的方式執行特定任務。 **提示的特徵:** - **範本化**:可重複使用的指令格式 - **參數化**:接受動態參數填入 - **標準化**:確保一致的輸出品質 - **專業化**:針對特定領域優化 ### 提示定義與使用 **基礎提示定義:** ```json { "name": "analyze_customer_feedback", "title": "客戶回饋分析提示", "description": "分析客戶回饋並提供改善建議", "arguments": [ { "name": "feedback_text", "description": "客戶回饋內容", "type": "string", "required": true }, { "name": "product_category", "description": "產品類別", "type": "string", "required": true }, { "name": "analysis_depth", "description": "分析深度", "type": "string", "enum": ["basic", "detailed", "comprehensive"], "default": "detailed" } ] } ``` **提示模板內容:** ```python class CustomerFeedbackPrompt: def __init__(self): self.template = """ 你是一位專業的客戶體驗分析師。請分析以下客戶回饋: **客戶回饋內容:** {feedback_text} **產品類別:** {product_category} **分析要求:** 請根據以下架構進行{analysis_depth}分析: 1. **情感分析** - 整體情感傾向(正面/中性/負面) - 情感強度評分(1-10) - 關鍵情感詞彙 2. **問題識別** - 明確指出的問題 - 隱含的問題 - 問題嚴重程度評估 3. **改善建議** - 短期改善措施 - 長期策略建議 - 實施優先級 4. **後續行動** - 建議回應方式 - 內部溝通要點 - 追蹤指標建議 請確保分析客觀、具體,並提供可行的建議。 """ async def generate(self, **kwargs) -> str: """生成具體的提示內容""" return self.template.format(**kwargs) ``` ### 動態提示組合 **情境感知的提示選擇:** ```python class AdaptivePromptManager: def __init__(self): self.prompt_library = {} self.context_analyzer = ContextAnalyzer() async def get_optimal_prompt(self, task: str, context: dict) -> str: """根據任務和上下文選擇最佳提示""" # 分析任務類型 task_type = self.context_analyzer.classify_task(task) # 評估上下文複雜度 complexity = self.context_analyzer.assess_complexity(context) # 選擇合適的提示模板 if task_type == "analysis" and complexity == "high": prompt_name = "comprehensive_analysis" elif task_type == "analysis" and complexity == "medium": prompt_name = "standard_analysis" else: prompt_name = "basic_analysis" # 生成個性化提示 base_prompt = self.prompt_library[prompt_name] return await self._customize_prompt(base_prompt, context) ``` ## 三大機制的協作模式 ### 場景一:智慧客服系統 **工作流程:** ``` 1. 客戶詢問產品問題 ↓ 2. AI 使用 Resource 獲取產品資料庫資訊 ↓ 3. AI 使用 Prompt 模板分析客戶需求 ↓ 4. AI 使用 Tool 查詢庫存和價格 ↓ 5. AI 基於 Prompt 生成個性化回應 ``` **實際實現:** ```python async def handle_customer_inquiry(inquiry: str, customer_id: str): # 1. 獲取客戶歷史資料 (Resource) customer_history = await mcp_client.get_resource( f"customer://profile/{customer_id}" ) # 2. 獲取產品資訊 (Resource) product_catalog = await mcp_client.get_resource( "catalog://products/current" ) # 3. 分析客戶意圖 (Tool) intent_analysis = await mcp_client.call_tool( "analyze_customer_intent", {"text": inquiry, "customer_context": customer_history} ) # 4. 查詢相關產品 (Tool) relevant_products = await mcp_client.call_tool( "search_products", {"query": intent_analysis.keywords, "category": intent_analysis.category} ) # 5. 生成回應 (Prompt) response_prompt = await mcp_client.get_prompt( "customer_service_response", { "customer_type": customer_history.tier, "inquiry_type": intent_analysis.type, "products": relevant_products, "tone": "friendly_professional" } ) return response_prompt ``` ### 場景二:數據分析報告生成 **協作流程:** ```python async def generate_business_report(report_type: str, date_range: dict): # 1. 獲取數據源配置 (Resource) data_sources = await mcp_client.get_resource("config://data_sources") # 2. 提取原始數據 (Tool) raw_data = await mcp_client.call_tool( "extract_business_data", { "sources": data_sources.databases, "start_date": date_range.start, "end_date": date_range.end, "metrics": ["revenue", "customers", "orders"] } ) # 3. 數據清洗和處理 (Tool) processed_data = await mcp_client.call_tool( "process_data", {"raw_data": raw_data, "cleaning_rules": "standard"} ) # 4. 獲取分析模板 (Resource) analysis_template = await mcp_client.get_resource( f"template://analysis/{report_type}" ) # 5. 執行分析 (Tool) analysis_results = await mcp_client.call_tool( "perform_analysis", { "data": processed_data, "template": analysis_template, "analysis_type": report_type } ) # 6. 生成最終報告 (Prompt) final_report = await mcp_client.get_prompt( "business_report_generation", { "report_type": report_type, "data_summary": analysis_results.summary, "key_insights": analysis_results.insights, "recommendations": analysis_results.recommendations, "format": "executive_summary" } ) return final_report ``` ## 台灣企業應用最佳實踐 ### 製造業 IoT 監控系統 **Tools 設計:** ```python # 設備控制工具 tools = [ "read_sensor_data", # 讀取感測器數據 "adjust_machine_speed", # 調整機器速度 "trigger_maintenance", # 觸發維護程序 "generate_alarm" # 產生警報 ] ``` **Resources 配置:** ```python # 生產線資源 resources = [ "config://factory/production_lines", # 生產線配置 "manual://equipment/operation", # 設備操作手冊 "schedule://maintenance/weekly", # 維護排程 "specs://quality/standards" # 品質標準 ] ``` **Prompts 模板:** ```python # 異常處理提示 prompts = [ "equipment_failure_analysis", # 設備故障分析 "quality_deviation_response", # 品質偏差處理 "maintenance_scheduling", # 維護排程建議 "production_optimization" # 生產最佳化建議 ] ``` ### 金融業風險管控 **整合範例:** ```python async def assess_credit_risk(application_id: str): # 獲取申請人資料 (Resource) applicant_data = await get_resource(f"customer://application/{application_id}") # 查詢信用紀錄 (Tool) credit_history = await call_tool("query_credit_bureau", { "customer_id": applicant_data.customer_id, "scope": "comprehensive" }) # 執行風險評估 (Tool) risk_score = await call_tool("calculate_risk_score", { "applicant_data": applicant_data, "credit_history": credit_history, "model": "latest_ml_model" }) # 生成風險報告 (Prompt) risk_report = await get_prompt("credit_risk_assessment", { "applicant_info": applicant_data, "risk_score": risk_score, "recommendations": risk_score.recommendations, "compliance_notes": "金管會規範" }) return risk_report ``` ## 開發最佳實踐 ### 工具設計原則 1. **單一職責**:每個工具只做一件事,做好一件事 2. **參數驗證**:嚴格驗證輸入參數,提供清晰的錯誤訊息 3. **錯誤處理**:優雅地處理各種異常情況 4. **效能最佳化**:避免不必要的計算和 I/O 操作 5. **文件完整**:提供詳細的描述和使用範例 ### 資源管理策略 1. **快取機制**:對靜態資源實施智能快取 2. **版本控制**:追蹤資源版本變化 3. **權限控制**:確保資源訪問安全 4. **監控告警**:監控資源使用情況和效能 ### 提示最佳化技巧 1. **A/B 測試**:測試不同提示模板的效果 2. **動態調整**:根據回饋調整提示內容 3. **領域專精**:為不同領域設計專門的提示 4. **多語言支援**:提供多語言版本的提示 ## 小結:三位一體的智能協作 Tools、Resources、Prompts 三大機制的設計體現了 MCP 的核心理念:**讓 AI 具備真正的實用性和專業性**。 - **Tools** 賦予 AI 「動手能力」,讓它能夠執行實際操作 - **Resources** 提供 AI 「背景知識」,讓它擁有豐富的上下文 - **Prompts** 指導 AI 「工作方式」,確保輸出的專業性和一致性 這三者的完美結合,讓 AI 從「會聊天的機器人」進化成「專業的工作夥伴」,這正是 MCP 技術的革命性價值所在。 --- **下一頁:** [2-3 上下文管理與持久化技術](/s/mcp-context-management)