koch3092 commited on
Commit
1ccc56a
·
1 Parent(s): d02f3a5

feat: add mcp sample

Browse files
owl/run_mcp.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # run_mcp.py
2
+
3
+ import asyncio
4
+ import sys
5
+ from pathlib import Path
6
+ from typing import List
7
+
8
+ from dotenv import load_dotenv
9
+
10
+ from camel.models import ModelFactory
11
+ from camel.toolkits import MCPToolkit, FunctionTool
12
+ from camel.types import ModelPlatformType, ModelType
13
+ from camel.logger import set_log_level
14
+
15
+ from utils.async_role_playing import OwlRolePlaying, run_society
16
+
17
+ from utils.mcp.mcp_toolkit_manager import MCPToolkitManager
18
+
19
+
20
+ load_dotenv()
21
+ set_log_level(level="DEBUG")
22
+
23
+
24
+ async def construct_society(
25
+ question: str,
26
+ tools: List[FunctionTool],
27
+ ) -> OwlRolePlaying:
28
+ """
29
+ 构建一个多Agent的OwlRolePlaying实例。
30
+ 这里的tools已经是用户想交给assistant使用的全部Tool集合。
31
+ """
32
+ # 1. 创建模型
33
+ models = {
34
+ "user": ModelFactory.create(
35
+ model_platform=ModelPlatformType.OPENAI,
36
+ model_type=ModelType.GPT_4O,
37
+ model_config_dict={"temperature": 0},
38
+ ),
39
+ "assistant": ModelFactory.create(
40
+ model_platform=ModelPlatformType.OPENAI,
41
+ model_type=ModelType.GPT_4O,
42
+ model_config_dict={"temperature": 0},
43
+ ),
44
+ }
45
+
46
+ # 2. 配置User和Assistant
47
+ user_agent_kwargs = {"model": models["user"]}
48
+ assistant_agent_kwargs = {
49
+ "model": models["assistant"],
50
+ "tools": tools, # 直接使用外部提供的全部tools
51
+ }
52
+
53
+ # 3. 设置任务参数
54
+ task_kwargs = {
55
+ "task_prompt": question,
56
+ "with_task_specify": False,
57
+ }
58
+
59
+ # 4. 构造并返回OwlRolePlaying
60
+ society = OwlRolePlaying(
61
+ **task_kwargs,
62
+ user_role_name="user",
63
+ user_agent_kwargs=user_agent_kwargs,
64
+ assistant_role_name="assistant",
65
+ assistant_agent_kwargs=assistant_agent_kwargs,
66
+ )
67
+ return society
68
+
69
+
70
+ async def main():
71
+ # 准备MCP Servers
72
+ config_path = str(
73
+ Path(__file__).parent / "utils/mcp/mcp_servers_config.json"
74
+ )
75
+
76
+ manager = MCPToolkitManager.from_config(config_path)
77
+
78
+ # 示例问题
79
+ question = (
80
+ "I'd like a academic report about Guohao Li, including his research "
81
+ "direction, published papers (up to 20), institutions, etc."
82
+ "Then organize the report in Markdown format and save it to my desktop"
83
+ )
84
+
85
+ # 在main中统一用async with把所有MCP连接打开
86
+ async with manager.connection():
87
+ # 这里 manager.is_connected() = True
88
+ # 获取合并后的tools
89
+ tools = manager.get_all_tools()
90
+
91
+ # 构造Society
92
+ society = await construct_society(question, tools)
93
+
94
+ # 运行对话
95
+ answer, chat_history, token_count = await run_society(society)
96
+
97
+ # 出了 with 块,这些toolkit就全部关闭
98
+ # manager.is_connected() = False
99
+
100
+ # 打印结果
101
+ print(f"\033[94mAnswer: {answer}\033[0m")
102
+ print("Chat History:", chat_history)
103
+ print("Token Count:", token_count)
104
+
105
+
106
+ if __name__ == "__main__":
107
+ asyncio.run(main())
owl/utils/async_role_playing.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, List
2
+
3
+ from camel.agents import ChatAgent
4
+ from camel.responses import ChatAgentResponse
5
+ from camel.messages.base import BaseMessage
6
+ from camel.societies import RolePlaying
7
+ from camel.logger import get_logger
8
+
9
+
10
+ from copy import deepcopy
11
+
12
+ logger = get_logger(__name__)
13
+
14
+
15
+ class OwlRolePlaying(RolePlaying):
16
+ def __init__(self, **kwargs):
17
+ self.user_role_name = kwargs.get("user_role_name", "user")
18
+ self.assistant_role_name = kwargs.get("assistant_role_name", "assistant")
19
+
20
+ self.output_language = kwargs.get("output_language", None)
21
+
22
+ self.user_agent_kwargs = kwargs.get("user_agent_kwargs", {})
23
+ self.assistant_agent_kwargs = kwargs.get("assistant_agent_kwargs", {})
24
+
25
+ super().__init__(**kwargs)
26
+
27
+ init_user_sys_msg, init_assistant_sys_msg = self._construct_gaia_sys_msgs()
28
+
29
+ self.assistant_agent: ChatAgent
30
+ self.user_agent: ChatAgent
31
+ self.assistant_sys_msg: Optional[BaseMessage]
32
+ self.user_sys_msg: Optional[BaseMessage]
33
+
34
+ self._init_agents(
35
+ init_assistant_sys_msg,
36
+ init_user_sys_msg,
37
+ assistant_agent_kwargs=self.assistant_agent_kwargs,
38
+ user_agent_kwargs=self.user_agent_kwargs,
39
+ output_language=self.output_language,
40
+ # is_reasoning_task=self.is_reasoning_task
41
+ )
42
+
43
+ def _construct_gaia_sys_msgs(self):
44
+ user_system_prompt = f"""
45
+ ===== RULES OF USER =====
46
+ Never forget you are a user and I am a assistant. Never flip roles! You will always instruct me. We share a common interest in collaborating to successfully complete a task.
47
+ I must help you to complete a difficult task.
48
+ You must instruct me based on my expertise and your needs to solve the task step by step. The format of your instruction is: `Instruction: [YOUR INSTRUCTION]`, where "Instruction" describes a sub-task or question.
49
+ You must give me one instruction at a time.
50
+ I must write a response that appropriately solves the requested instruction.
51
+ You should instruct me not ask me questions.
52
+
53
+ Please note that the task may be very complicated. Do not attempt to solve the task by single step. You must instruct me to find the answer step by step.
54
+ Here are some tips that will help you to give more valuable instructions about our task to me:
55
+ <tips>
56
+ - I have various tools to use, such as search toolkit, web browser simulation toolkit, document relevant toolkit, code execution toolkit, etc. Thus, You must think how human will solve the task step-by-step, and give me instructions just like that. For example, one may first use google search to get some initial information and the target url, then retrieve the content of the url, or do some web browser interaction to find the answer.
57
+ - Although the task is complex, the answer does exist. If you can’t find the answer using the current scheme, try to re-plan and use other ways to find the answer, e.g. using other tools or methods that can achieve similar results.
58
+ - Always remind me to verify my final answer about the overall task. This work can be done by using multiple tools(e.g., screenshots, webpage analysis, etc.), or something else.
59
+ - If I have written code, please remind me to run the code and get the result.
60
+ - Search results typically do not provide precise answers. It is not likely to find the answer directly using search toolkit only, the search query should be concise and focuses on finding sources rather than direct answers, as it always need to use other tools to further process the url, e.g. interact with the webpage, extract webpage content, etc.
61
+ - If the question mentions youtube video, in most cases you have to process the content of the mentioned video.
62
+ - For downloading files, you can either use the web browser simulation toolkit or write codes (for example, the github content can be downloaded via https://raw.githubusercontent.com/...).
63
+ - Flexibly write codes to solve some problems, such as excel relevant tasks.
64
+ </tips>
65
+
66
+ Now, here is the overall task: <task>{self.task_prompt}</task>. Never forget our task!
67
+
68
+ Now you must start to instruct me to solve the task step-by-step. Do not add anything else other than your instruction!
69
+ Keep giving me instructions until you think the task is completed.
70
+ When the task is completed, you must only reply with a single word <TASK_DONE>.
71
+ Never say <TASK_DONE> unless my responses have solved your task.
72
+ """
73
+
74
+ assistant_system_prompt = f"""
75
+ ===== RULES OF ASSISTANT =====
76
+ Never forget you are a assistant and I am a user. Never flip roles! Never instruct me! You have to utilize your available tools to solve the task I assigned.
77
+ We share a common interest in collaborating to successfully complete a complex task.
78
+ You must help me to complete the task.
79
+
80
+ Here is our overall task: {self.task_prompt}. Never forget our task!
81
+
82
+ I must instruct you based on your expertise and my needs to complete the task. An instruction is typically a sub-task or question.
83
+
84
+ You must leverage your available tools, try your best to solve the problem, and explain your solutions.
85
+ Unless I say the task is completed, you should always start with:
86
+ Solution: [YOUR_SOLUTION]
87
+ [YOUR_SOLUTION] should be specific, including detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.
88
+
89
+ Please note that our overall task may be very complicated. Here are some tips that may help you solve the task:
90
+ <tips>
91
+ - If one way fails to provide an answer, try other ways or methods. The answer does exists.
92
+ - If the search snippet is unhelpful but the URL comes from an authoritative source, try visit the website for more details.
93
+ - When looking for specific numerical values (e.g., dollar amounts), prioritize reliable sources and avoid relying only on search snippets.
94
+ - When solving tasks that require web searches, check Wikipedia first before exploring other websites.
95
+ - When trying to solve math problems, you can try to write python code and use sympy library to solve the problem.
96
+ - Always verify the accuracy of your final answers! Try cross-checking the answers by other ways. (e.g., screenshots, webpage analysis, etc.).
97
+ - Do not be overly confident in your own knowledge. Searching can provide a broader perspective and help validate existing knowledge.
98
+ - After writing codes, do not forget to run the code and get the result. If it encounters an error, try to debug it.
99
+ - When a tool fails to run, or the code does not run correctly, never assume that it returns the correct result and continue to reason based on the assumption, because the assumed result cannot lead you to the correct answer. The right way is to think about the reason for the error and try again.
100
+ - Search results typically do not provide precise answers. It is not likely to find the answer directly using search toolkit only, the search query should be concise and focuses on finding sources rather than direct answers, as it always need to use other tools to further process the url, e.g. interact with the webpage, extract webpage content, etc.
101
+ - For downloading files, you can either use the web browser simulation toolkit or write codes.
102
+ </tips>
103
+
104
+ """
105
+
106
+ user_sys_msg = BaseMessage.make_user_message(
107
+ role_name=self.user_role_name, content=user_system_prompt
108
+ )
109
+
110
+ assistant_sys_msg = BaseMessage.make_assistant_message(
111
+ role_name=self.assistant_role_name, content=assistant_system_prompt
112
+ )
113
+
114
+ return user_sys_msg, assistant_sys_msg
115
+
116
+ async def astep(
117
+ self,
118
+ assistant_msg: BaseMessage
119
+ ) -> Tuple[ChatAgentResponse, ChatAgentResponse]:
120
+ user_response = await self.user_agent.astep(assistant_msg)
121
+ if user_response.terminated or user_response.msgs is None:
122
+ return (
123
+ ChatAgentResponse(msgs=[], terminated=False, info={}),
124
+ ChatAgentResponse(
125
+ msgs=[],
126
+ terminated=user_response.terminated,
127
+ info=user_response.info,
128
+ ),
129
+ )
130
+ user_msg = self._reduce_message_options(user_response.msgs)
131
+
132
+ modified_user_msg = deepcopy(user_msg)
133
+
134
+ if "TASK_DONE" not in user_msg.content:
135
+ modified_user_msg.content += f"""\n
136
+ Here are auxiliary information about the overall task, which may help you understand the intent of the current task:
137
+ <auxiliary_information>
138
+ {self.task_prompt}
139
+ </auxiliary_information>
140
+ If there are available tools and you want to call them, never say 'I will ...', but first call the tool and reply based on tool call's result, and tell me which tool you have called.
141
+ """
142
+
143
+ else:
144
+ # The task is done, and the assistant agent need to give the final answer about the original task
145
+ modified_user_msg.content += f"""\n
146
+ Now please make a final answer of the original task based on our conversation : <task>{self.task_prompt}</task>
147
+ """
148
+
149
+ assistant_response = await self.assistant_agent.astep(user_msg)
150
+ if assistant_response.terminated or assistant_response.msgs is None:
151
+ return (
152
+ ChatAgentResponse(
153
+ msgs=[],
154
+ terminated=assistant_response.terminated,
155
+ info=assistant_response.info,
156
+ ),
157
+ ChatAgentResponse(
158
+ msgs=[user_msg], terminated=False, info=user_response.info
159
+ ),
160
+ )
161
+ assistant_msg = self._reduce_message_options(assistant_response.msgs)
162
+
163
+ modified_assistant_msg = deepcopy(assistant_msg)
164
+ if "TASK_DONE" not in user_msg.content:
165
+ modified_assistant_msg.content += f"""\n
166
+ Provide me with the next instruction and input (if needed) based on my response and our current task: <task>{self.task_prompt}</task>
167
+ Before producing the final answer, please check whether I have rechecked the final answer using different toolkit as much as possible. If not, please remind me to do that.
168
+ If I have written codes, remind me to run the codes.
169
+ If you think our task is done, reply with `TASK_DONE` to end our conversation.
170
+ """
171
+
172
+ return (
173
+ ChatAgentResponse(
174
+ msgs=[assistant_msg],
175
+ terminated=assistant_response.terminated,
176
+ info=assistant_response.info,
177
+ ),
178
+ ChatAgentResponse(
179
+ msgs=[user_msg],
180
+ terminated=user_response.terminated,
181
+ info=user_response.info,
182
+ ),
183
+ )
184
+
185
+
186
+ async def run_society(
187
+ society: OwlRolePlaying,
188
+ round_limit: int = 15,
189
+ ) -> Tuple[str, List[dict], dict]:
190
+ overall_completion_token_count = 0
191
+ overall_prompt_token_count = 0
192
+
193
+ chat_history = []
194
+ init_prompt = """
195
+ Now please give me instructions to solve over overall task step by step. If the task requires some specific knowledge, please instruct me to use tools to complete the task.
196
+ """
197
+ input_msg = society.init_chat(init_prompt)
198
+ for _round in range(round_limit):
199
+ assistant_response, user_response = await society.astep(input_msg)
200
+ overall_prompt_token_count += (
201
+ assistant_response.info["usage"]["completion_tokens"]
202
+ )
203
+ overall_prompt_token_count += (
204
+ assistant_response.info["usage"]["prompt_tokens"]
205
+ + user_response.info["usage"]["prompt_tokens"]
206
+ )
207
+
208
+ # convert tool call to dict
209
+ tool_call_records: List[dict] = []
210
+ for tool_call in assistant_response.info["tool_calls"]:
211
+ tool_call_records.append(tool_call.as_dict())
212
+
213
+ _data = {
214
+ "user": user_response.msg.content,
215
+ "assistant": assistant_response.msg.content,
216
+ "tool_calls": tool_call_records,
217
+ }
218
+
219
+ chat_history.append(_data)
220
+ logger.info(f"Round #{_round} user_response:\n {user_response.msgs[0].content}")
221
+ logger.info(
222
+ f"Round #{_round} assistant_response:\n {assistant_response.msgs[0].content}"
223
+ )
224
+
225
+ if (
226
+ assistant_response.terminated
227
+ or user_response.terminated
228
+ or "TASK_DONE" in user_response.msg.content
229
+ ):
230
+ break
231
+
232
+ input_msg = assistant_response.msg
233
+
234
+ answer = chat_history[-1]["assistant"]
235
+ token_info = {
236
+ "completion_token_count": overall_completion_token_count,
237
+ "prompt_token_count": overall_prompt_token_count,
238
+ }
239
+
240
+ return answer, chat_history, token_info
owl/utils/mcp/__init__.py ADDED
File without changes
owl/utils/mcp/mcp_servers_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mcpServers": {
3
+ "filesystem": {
4
+ "command": "mcp-filesystem-server",
5
+ "args": [
6
+ "/Users/coco/Desktop",
7
+ "/Users/coco/Downloads"
8
+ ]
9
+ },
10
+ "simple-arxiv": {
11
+ "command": "python",
12
+ "args": ["-m", "mcp_simple_arxiv"]
13
+ }
14
+ },
15
+ "mcpWebServers": {
16
+ "weather": {
17
+ "url": "https://c9a9-89-185-25-132.ngrok-free.app/sse"
18
+ }
19
+ }
20
+ }
owl/utils/mcp/mcp_toolkit_manager.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from typing import List, Optional, AsyncGenerator
4
+
5
+ from camel.toolkits import MCPToolkit
6
+ from contextlib import AsyncExitStack, asynccontextmanager
7
+
8
+
9
+ class MCPToolkitManager:
10
+ """
11
+ 负责管理多个 MCPToolkit 实例,并提供统一的连接管理。
12
+ """
13
+
14
+ def __init__(self, toolkits: List[MCPToolkit]):
15
+ self.toolkits = toolkits
16
+ self._exit_stack: Optional[AsyncExitStack] = None
17
+ self._connected = False
18
+
19
+
20
+ @staticmethod
21
+ def from_config(config_path: str) -> "MCPToolkitManager":
22
+ """从 JSON 配置文件加载 MCPToolkit 实例,并返回 MCPToolkitManager 实例。
23
+
24
+ :param config_path: JSON 配置文件路径
25
+ :return: MCPToolkitManager 实例
26
+ """
27
+ with open(config_path, "r", encoding="utf-8") as f:
28
+ data = json.load(f)
29
+
30
+ all_toolkits = []
31
+
32
+ # 处理本地 MCP 服务器
33
+ mcp_servers = data.get("mcpServers", {})
34
+ for name, cfg in mcp_servers.items():
35
+ toolkit = MCPToolkit(
36
+ command_or_url=cfg["command"],
37
+ args=cfg.get("args", []),
38
+ env={**os.environ, **cfg.get("env", {})},
39
+ timeout=cfg.get("timeout", None),
40
+ )
41
+ all_toolkits.append(toolkit)
42
+
43
+ # 处理远程 MCP Web 服务器
44
+ mcp_web_servers = data.get("mcpWebServers", {})
45
+ for name, cfg in mcp_web_servers.items():
46
+ toolkit = MCPToolkit(
47
+ command_or_url=cfg["url"],
48
+ timeout=cfg.get("timeout", None),
49
+ )
50
+ all_toolkits.append(toolkit)
51
+
52
+ return MCPToolkitManager(all_toolkits)
53
+
54
+ @asynccontextmanager
55
+ async def connection(self) -> AsyncGenerator["MCPToolkitManager", None]:
56
+ """统一打开多个 MCPToolkit 的连接,并在离开上下文时关闭。"""
57
+ self._exit_stack = AsyncExitStack()
58
+ try:
59
+ # 顺序进入每个 toolkit 的 async context
60
+ for tk in self.toolkits:
61
+ await self._exit_stack.enter_async_context(tk.connection())
62
+ self._connected = True
63
+ yield self
64
+ finally:
65
+ self._connected = False
66
+ await self._exit_stack.aclose()
67
+ self._exit_stack = None
68
+
69
+ def is_connected(self) -> bool:
70
+ return self._connected
71
+
72
+ def get_all_tools(self):
73
+ """合并所有 MCPToolkit 提供的工具"""
74
+ all_tools = []
75
+ for tk in self.toolkits:
76
+ all_tools.extend(tk.get_tools())
77
+ return all_tools
owl/utils/mcp/servers/__init__.py ADDED
File without changes
owl/utils/mcp/servers/mcp_server.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+ from typing import Any
15
+
16
+ import httpx
17
+ from mcp.server.fastmcp import FastMCP
18
+
19
+ mcp = FastMCP("weather")
20
+
21
+ NWS_API_BASE = "https://api.weather.gov"
22
+ USER_AGENT = "weather-app/1.0"
23
+
24
+
25
+ async def make_nws_request(url: str) -> dict[str, Any] | None:
26
+ r"""Make a request to the NWS API with proper error handling."""
27
+ headers = {"User-Agent": USER_AGENT, "Accept": "application/geo+json"}
28
+ async with httpx.AsyncClient() as client:
29
+ try:
30
+ response = await client.get(url, headers=headers, timeout=30.0)
31
+ response.raise_for_status()
32
+ return response.json()
33
+ except Exception:
34
+ return None
35
+
36
+
37
+ def format_alert(feature: dict) -> str:
38
+ r"""Format an alert feature into a readable string."""
39
+ props = feature["properties"]
40
+ return f"""
41
+ Event: {props.get('event', 'Unknown')}
42
+ Area: {props.get('areaDesc', 'Unknown')}
43
+ Severity: {props.get('severity', 'Unknown')}
44
+ Description: {props.get('description', 'No description available')}
45
+ Instructions: {props.get('instruction', 'No specific instructions provided')}
46
+ """
47
+
48
+
49
+ @mcp.tool()
50
+ async def get_alerts(state: str) -> str:
51
+ r"""Get weather alerts for a US state.
52
+
53
+ Args:
54
+ state: Two-letter US state code (e.g. CA, NY)
55
+ """
56
+ url = f"{NWS_API_BASE}/alerts/active/area/{state}"
57
+ data = await make_nws_request(url)
58
+
59
+ if not data or "features" not in data:
60
+ return "Unable to fetch alerts or no alerts found."
61
+
62
+ if not data["features"]:
63
+ return "No active alerts for this state."
64
+
65
+ alerts = [format_alert(feature) for feature in data["features"]]
66
+ return "\n---\n".join(alerts)
67
+
68
+
69
+ @mcp.tool()
70
+ async def get_forecast(latitude: float, longitude: float) -> str:
71
+ r"""Get weather forecast for a location.
72
+
73
+ Args:
74
+ latitude: Latitude of the location
75
+ longitude: Longitude of the location
76
+ """
77
+ # First get the forecast grid endpoint
78
+ points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
79
+ points_data = await make_nws_request(points_url)
80
+
81
+ if not points_data:
82
+ return "Unable to fetch forecast data for this location."
83
+
84
+ # Get the forecast URL from the points response
85
+ forecast_url = points_data["properties"]["forecast"]
86
+ forecast_data = await make_nws_request(forecast_url)
87
+
88
+ if not forecast_data:
89
+ return "Unable to fetch detailed forecast."
90
+
91
+ # Format the periods into a readable forecast
92
+ periods = forecast_data["properties"]["periods"]
93
+ forecasts = []
94
+ for period in periods[:5]: # Only show next 5 periods
95
+ forecast = f"""
96
+ {period['name']}:
97
+ Temperature: {period['temperature']}°{period['temperatureUnit']}
98
+ Wind: {period['windSpeed']} {period['windDirection']}
99
+ Forecast: {period['detailedForecast']}
100
+ """
101
+ forecasts.append(forecast)
102
+
103
+ return "\n---\n".join(forecasts)
104
+
105
+
106
+ def main(transport: str = "stdio"):
107
+ r"""Weather MCP Server
108
+
109
+ This server provides weather-related functionalities implemented via the Model Context Protocol (MCP).
110
+ It demonstrates how to establish interactions between AI models and external tools using MCP.
111
+
112
+ The server supports two modes of operation:
113
+
114
+ 1. stdio mode (default):
115
+
116
+ - Communicates with clients via standard input/output streams, ideal for local command-line usage.
117
+
118
+ - Example usage: python mcp_server.py [--transport stdio]
119
+
120
+ 2. SSE mode (Server-Sent Events):
121
+
122
+ - Communicates with clients over HTTP using server-sent events, suitable for persistent network connections.
123
+
124
+ - Runs by default at http://127.0.0.1:8000.
125
+
126
+ - Example usage: python mcp_server.py --transport sse
127
+ """ # noqa: E501
128
+ if transport == 'stdio':
129
+ mcp.run(transport='stdio')
130
+ elif transport == 'sse':
131
+ mcp.run(transport='sse')
132
+
133
+
134
+ if __name__ == "__main__":
135
+ # Hardcoded to use stdio transport mode
136
+ main("stdio")
requirements.txt CHANGED
@@ -1,4 +1,4 @@
1
- camel-ai[all]==0.2.23
2
  chunkr-ai>=0.0.41
3
  docx2markdown>=0.1.1
4
  gradio>=3.50.2
 
1
+ camel-ai[all]==0.2.24
2
  chunkr-ai>=0.0.41
3
  docx2markdown>=0.1.1
4
  gradio>=3.50.2