Add pyright strict mode on the whole project (#1254)

This commit is contained in:
Marcelo Trylesinski 2025-08-11 19:56:37 +02:00 • committed by GitHub
commit c7671e470c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 652 additions and 674 deletions

View file

@ -188,9 +188,7 @@ class SimpleAuthClient:
# Create OAuth authentication handler using the new interface
oauth_auth = OAuthClientProvider(
server_url=self.server_url.replace("/mcp", ""),
client_metadata=OAuthClientMetadata.model_validate(
client_metadata_dict
),
client_metadata=OAuthClientMetadata.model_validate(client_metadata_dict),
storage=InMemoryTokenStorage(),
redirect_handler=_default_redirect_handler,
callback_handler=callback_handler,
@ -322,9 +320,7 @@ class SimpleAuthClient:
await self.call_tool(tool_name, arguments)
else:
print(
"❌ Unknown command. Try 'list', 'call <tool_name>', or 'quit'"
)
print("❌ Unknown command. Try 'list', 'call <tool_name>', or 'quit'")
except KeyboardInterrupt:
print("\n\n👋 Goodbye!")

View file

@ -39,7 +39,7 @@ select = ["E", "F", "I"]
ignore = []
[tool.ruff]
line-length = 88
line-length = 120
target-version = "py310"
[tool.uv]

View file

@ -12,9 +12,7 @@ from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
class Configuration:
@ -75,29 +73,19 @@ class Server:
async def initialize(self) -> None:
"""Initialize the server connection."""
command = (
shutil.which("npx")
if self.config["command"] == "npx"
else self.config["command"]
)
command = shutil.which("npx") if self.config["command"] == "npx" else self.config["command"]
if command is None:
raise ValueError("The command must be a valid string and cannot be None.")
server_params = StdioServerParameters(
command=command,
args=self.config["args"],
env={**os.environ, **self.config["env"]}
if self.config.get("env")
else None,
env={**os.environ, **self.config["env"]} if self.config.get("env") else None,
)
try:
stdio_transport = await self.exit_stack.enter_async_context(
stdio_client(server_params)
)
stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))
read, write = stdio_transport
session = await self.exit_stack.enter_async_context(
ClientSession(read, write)
)
session = await self.exit_stack.enter_async_context(ClientSession(read, write))
await session.initialize()
self.session = session
except Exception as e:
@ -122,10 +110,7 @@ class Server:
for item in tools_response:
if isinstance(item, tuple) and item[0] == "tools":
tools.extend(
Tool(tool.name, tool.description, tool.inputSchema, tool.title)
for tool in item[1]
)
tools.extend(Tool(tool.name, tool.description, tool.inputSchema, tool.title) for tool in item[1])
return tools
@ -164,9 +149,7 @@ class Server:
except Exception as e:
attempt += 1
logging.warning(
f"Error executing tool: {e}. Attempt {attempt} of {retries}."
)
logging.warning(f"Error executing tool: {e}. Attempt {attempt} of {retries}.")
if attempt < retries:
logging.info(f"Retrying in {delay} seconds...")
await asyncio.sleep(delay)
@ -209,9 +192,7 @@ class Tool:
args_desc = []
if "properties" in self.input_schema:
for param_name, param_info in self.input_schema["properties"].items():
arg_desc = (
f"- {param_name}: {param_info.get('description', 'No description')}"
)
arg_desc = f"- {param_name}: {param_info.get('description', 'No description')}"
if param_name in self.input_schema.get("required", []):
arg_desc += " (required)"
args_desc.append(arg_desc)
@ -281,10 +262,7 @@ class LLMClient:
logging.error(f"Status code: {status_code}")
logging.error(f"Response details: {e.response.text}")
return (
f"I encountered an error: {error_message}. "
"Please try again or rephrase your request."
)
return f"I encountered an error: {error_message}. Please try again or rephrase your request."
class ChatSession:
@ -323,17 +301,13 @@ class ChatSession:
tools = await server.list_tools()
if any(tool.name == tool_call["tool"] for tool in tools):
try:
result = await server.execute_tool(
tool_call["tool"], tool_call["arguments"]
)
result = await server.execute_tool(tool_call["tool"], tool_call["arguments"])
if isinstance(result, dict) and "progress" in result:
progress = result["progress"]
total = result["total"]
percentage = (progress / total) * 100
logging.info(
f"Progress: {progress}/{total} ({percentage:.1f}%)"
)
logging.info(f"Progress: {progress}/{total} ({percentage:.1f}%)")
return f"Tool execution result: {result}"
except Exception as e:
@ -408,9 +382,7 @@ class ChatSession:
final_response = self.llm_client.get_response(messages)
logging.info("\nFinal response: %s", final_response)
messages.append(
{"role": "assistant", "content": final_response}
)
messages.append({"role": "assistant", "content": final_response})
else:
messages.append({"role": "assistant", "content": llm_response})
@ -426,10 +398,7 @@ async def main() -> None:
"""Initialize and run the chat session."""
config = Configuration()
server_config = config.load_config("servers_config.json")
servers = [
Server(name, srv_config)
for name, srv_config in server_config["mcpServers"].items()
]
servers = [Server(name, srv_config) for name, srv_config in server_config["mcpServers"].items()]
llm_client = LLMClient(config.llm_api_key)
chat_session = ChatSession(servers, llm_client)
await chat_session.start()

View file

@ -41,7 +41,7 @@ select = ["E", "F", "I"]
ignore = []
[tool.ruff]
line-length = 88
line-length = 120
target-version = "py310"
[tool.uv]