Skip to content

Commit b70bfc9

Browse files
committed
fix up
Signed-off-by: SamYuan1990 <[email protected]>
1 parent efa6e32 commit b70bfc9

File tree

2 files changed

+32
-41
lines changed
  • examples

2 files changed

+32
-41
lines changed

examples/clients/homebrewupload-client/main.py

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,7 @@
1010
from mcp.client.session import ClientSession
1111
from mcp.client.sse import sse_client
1212

13-
logging.basicConfig(
14-
format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO
15-
)
13+
logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO)
1614

1715
load_dotenv() # load environment variables from .env
1816

@@ -45,7 +43,7 @@ async def connect_to_server(self):
4543
response = await self.session.list_tools()
4644
tools = response.tools
4745
print("\nConnected to server with tools:", [tool.name for tool in tools])
48-
46+
4947
return True
5048
except Exception as e:
5149
logging.error(f"Failed to connect to server: {e}")
@@ -56,23 +54,23 @@ async def process_chat(
5654
self,
5755
file_path: str | None = None,
5856
) -> str:
59-
""" Porcess a chat"""
57+
"""Porcess a chat"""
6058
messages = []
6159
user_content = """please help make file into markdown format, file path file:///tmp/test.pdf,
6260
you are free to use convert_to_markdown tool,
6361
the file will upload to MCP server in secure."""
6462

6563
try:
66-
with open(file_path,"rb") as f:
67-
file_content = base64.b64encode(f.read()).decode("utf-8")
68-
# 发送请求
64+
with open(file_path, "rb") as f:
65+
file_content = base64.b64encode(f.read()).decode("utf-8")
66+
# 发送请求
6967
response = requests.post(
70-
"http://localhost:3001/upload",
71-
json={"filename": "test.pdf", "file_content_base64": file_content},
68+
"http://localhost:3001/upload",
69+
json={"filename": "test.pdf", "file_content_base64": file_content},
7270
)
7371
except Exception as e:
74-
logging.info(f"file handle error: {str(e)}")
75-
return f"file handle error: {str(e)}"
72+
logging.info(f"file handle error: {str(e)}")
73+
return f"file handle error: {str(e)}"
7674
messages.append({"role": "user", "content": user_content})
7775
response = await self.session.list_tools()
7876
available_tools = [
@@ -95,7 +93,7 @@ async def process_chat(
9593
final_text.append(content.text)
9694
elif content.type == "tool_use":
9795
tool_name = content.name
98-
tool_args = "file:///tmp/test.pdf"#content.input
96+
tool_args = "file:///tmp/test.pdf" # content.input
9997

10098
# 执行工具调用
10199
try:
@@ -135,16 +133,15 @@ async def process_chat(
135133
for next_content in next_response.content:
136134
if next_content.type == "text":
137135
final_text.extend(
138-
next_content.text
139-
for next_content in next_response.content
140-
if next_content.type == "text"
141-
)
136+
next_content.text
137+
for next_content in next_response.content
138+
if next_content.type == "text"
139+
)
142140

143141
except Exception as e:
144142
final_text.append(f"tool invoke {tool_name} error: {str(e)}")
145143

146-
return "\n".join(final_text)
147-
144+
return "\n".join(final_text)
148145

149146
async def close(self):
150147
"""Properly close all connections"""

examples/servers/homebrewupload/main.py

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,14 @@
2222
# to different with markitdown official
2323
mcp = FastMCP("markitdown_homebrew")
2424

25+
2526
# Same with markitdown official
2627
@mcp.tool()
2728
async def convert_to_markdown(uri: str) -> str:
2829
"""Convert a resource described by an http:, https:, file: or data: URI to markdown"""
2930
return MarkItDown(enable_plugins=check_plugins_enabled()).convert_uri(uri).markdown
3031

32+
3133
# Same with markitdown official
3234
def check_plugins_enabled() -> bool:
3335
return os.getenv("MARKITDOWN_ENABLE_PLUGINS", "false").strip().lower() in (
@@ -36,6 +38,7 @@ def check_plugins_enabled() -> bool:
3638
"yes",
3739
)
3840

41+
3942
# Same with markitdown official
4043
def create_starlette_app(mcp_server: Server, *, debug: bool = False) -> Starlette:
4144
sse = SseServerTransport("/messages/")
@@ -58,9 +61,7 @@ async def handle_sse(request: Request) -> None:
5861
mcp_server.create_initialization_options(),
5962
)
6063

61-
async def handle_streamable_http(
62-
scope: Scope, receive: Receive, send: Send
63-
) -> None:
64+
async def handle_streamable_http(scope: Scope, receive: Receive, send: Send) -> None:
6465
await session_manager.handle_request(scope, receive, send)
6566

6667
@contextlib.asynccontextmanager
@@ -80,13 +81,12 @@ async def lifespan(app: Starlette) -> AsyncIterator[None]:
8081
Mount("/mcp", app=handle_streamable_http),
8182
Mount("/messages/", app=sse.handle_post_message),
8283
# adding this as URL path
83-
Route(
84-
"/upload", endpoint=handle_file_upload, methods=["POST"]
85-
),
84+
Route("/upload", endpoint=handle_file_upload, methods=["POST"]),
8685
],
8786
lifespan=lifespan,
8887
)
8988

89+
9090
# added function for handle file upload
9191
async def handle_file_upload(request: Request) -> JSONResponse:
9292
"""
@@ -103,29 +103,23 @@ async def handle_file_upload(request: Request) -> JSONResponse:
103103
return JSONResponse({"error": "Filename is required"}, status_code=400)
104104

105105
if not file_content_base64:
106-
return JSONResponse(
107-
{"error": "file_content_base64 is required"}, status_code=400
108-
)
106+
return JSONResponse({"error": "file_content_base64 is required"}, status_code=400)
109107
filename = os.path.basename(filename)
110108
file_path = os.path.join("/tmp/", filename)
111109
logging.info("start processing")
112110
try:
113111
file_data = base64.b64decode(file_content_base64)
114112
except Exception as e:
115113
logging.info(e)
116-
return JSONResponse(
117-
{"error": f"Invalid base64 data: {str(e)}"}, status_code=400
118-
)
114+
return JSONResponse({"error": f"Invalid base64 data: {str(e)}"}, status_code=400)
119115
os.makedirs("/tmp", exist_ok=True)
120116

121117
with open(file_path, "wb") as f:
122118
f.write(file_data)
123119

124120
if os.path.exists(file_path):
125121
file_size = os.path.getsize(file_path)
126-
logging.info(
127-
f"File saved successfully: {file_path}, size: {file_size} bytes"
128-
)
122+
logging.info(f"File saved successfully: {file_path}, size: {file_size} bytes")
129123

130124
return JSONResponse(
131125
{
@@ -144,20 +138,20 @@ async def handle_file_upload(request: Request) -> JSONResponse:
144138
return JSONResponse({"error": "Invalid JSON in request body"}, status_code=400)
145139
except Exception as e:
146140
logging.error(f"Error handling file upload: {str(e)}")
147-
return JSONResponse(
148-
{"error": f"Internal server error: {str(e)}"}, status_code=500
149-
)
141+
return JSONResponse({"error": f"Internal server error: {str(e)}"}, status_code=500)
142+
150143

151144
# Main entry point
152145
def main():
153146
mcp_server = mcp._mcp_server
154147
logging.info("start MCP server at 0.0.0.0:3001")
155148
starlette_app = create_starlette_app(mcp_server, debug=True)
156149
uvicorn.run(
157-
starlette_app,
158-
host="0.0.0.0",
159-
port=3001,
160-
)
150+
starlette_app,
151+
host="0.0.0.0",
152+
port=3001,
153+
)
154+
161155

162156
if __name__ == "__main__":
163157
main()

0 commit comments

Comments
 (0)