|
6 | 6 | you only need to implement the send_message tool. |
7 | 7 | """ |
8 | 8 |
|
| 9 | +from functools import lru_cache |
| 10 | + |
9 | 11 | from loguru import logger |
10 | 12 | from mcp.server.fastmcp import Context, FastMCP |
11 | | -from shirtify_agent import ShirtifyAgent |
12 | 13 | from starlette.requests import Request |
13 | 14 |
|
14 | | -agent = ShirtifyAgent() |
15 | | -mcp = FastMCP( |
16 | | - "shirtify_agent_mcp", |
17 | | - port=10001, |
18 | | - host="127.0.0.1", |
19 | | -) |
| 15 | +from .shirtify_agent import ShirtifyAgent |
| 16 | + |
| 17 | + |
| 18 | +@lru_cache(maxsize=1) |
| 19 | +def get_mcp_server(host: str = "127.0.0.1", port: int = 10001) -> FastMCP: |
| 20 | + agent = ShirtifyAgent() |
| 21 | + mcp = FastMCP( |
| 22 | + "shirtify_agent_mcp", |
| 23 | + host=host, |
| 24 | + port=port, |
| 25 | + ) |
20 | 26 |
|
| 27 | + @mcp.tool() |
| 28 | + def send_message(message: str, context: Context) -> str: |
| 29 | + session_id: str | None = None |
| 30 | + try: |
| 31 | + request: Request = context.request_context.request # type: ignore |
21 | 32 |
|
22 | | -@mcp.tool() |
23 | | -def send_message(message: str, context: Context) -> str: |
24 | | - session_id: str | None = None |
25 | | - try: |
26 | | - request: Request = context.request_context.request # type: ignore |
| 33 | + # The session id should be in the headers for streamable-http transport |
| 34 | + session_id = request.headers.get("mcp-session-id") |
27 | 35 |
|
28 | | - # The session id should be in the headers for streamable-http transport |
29 | | - session_id = request.headers.get("mcp-session-id") |
| 36 | + # The session id might also be in query param when using sse transport |
| 37 | + if session_id is None: |
| 38 | + session_id = request.query_params.get("session_id") |
| 39 | + except Exception: |
| 40 | + session_id = None |
| 41 | + logger.exception("Error while extracting session id") |
30 | 42 |
|
31 | | - # The session id might also be in query param when using sse transport |
32 | 43 | if session_id is None: |
33 | | - session_id = request.query_params.get("session_id") |
34 | | - except Exception: |
35 | | - session_id = None |
36 | | - logger.exception("Error while extracting session id") |
| 44 | + logger.error("Couldn't extract session id") |
37 | 45 |
|
38 | | - if session_id is None: |
39 | | - logger.error("Couldn't extract session id") |
| 46 | + # Invoking our agent |
| 47 | + response = agent.invoke(message, session_id) |
| 48 | + return response.get("content", "") |
40 | 49 |
|
41 | | - # Invoking our agent |
42 | | - response = agent.invoke(message, session_id) |
43 | | - return response.get("content", "") |
| 50 | + return mcp |
0 commit comments