Skip to content

Commit 1c2fa75

Browse files
committed
style: uv run ruff format
Signed-off-by: Samantha Coyle <sam@diagrid.io>
1 parent a9ceed3 commit 1c2fa75

11 files changed

Lines changed: 306 additions & 335 deletions

File tree

dapr/aio/clients/grpc/client.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,9 @@
8080
GetMetadataResponse,
8181
GetSecretResponse,
8282
InvokeMethodResponse,
83+
MetadataMCPServer,
8384
QueryResponse,
8485
QueryResponseItem,
85-
MetadataMCPServer,
8686
RegisteredComponents,
8787
StateResponse,
8888
TopicEventResponse,
@@ -1724,9 +1724,7 @@ async def get_metadata(self) -> GetMetadataResponse:
17241724
for i in response.registered_components
17251725
]
17261726
extended_metadata = dict(response.extended_metadata.items())
1727-
mcp_servers = [
1728-
MetadataMCPServer(name=s.name) for s in response.mcp_servers
1729-
]
1727+
mcp_servers = [MetadataMCPServer(name=s.name) for s in response.mcp_servers]
17301728

17311729
return GetMetadataResponse(
17321730
application_id=response.id,

dapr/clients/grpc/client.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,9 @@
7171
GetMetadataResponse,
7272
GetSecretResponse,
7373
InvokeMethodResponse,
74+
MetadataMCPServer,
7475
QueryResponse,
7576
QueryResponseItem,
76-
MetadataMCPServer,
7777
RegisteredComponents,
7878
StateResponse,
7979
TopicEventResponse,
@@ -1829,9 +1829,7 @@ def get_metadata(self) -> GetMetadataResponse:
18291829
for i in response.registered_components
18301830
]
18311831
extended_metadata = dict(response.extended_metadata.items())
1832-
mcp_servers = [
1833-
MetadataMCPServer(name=s.name) for s in response.mcp_servers
1834-
]
1832+
mcp_servers = [MetadataMCPServer(name=s.name) for s in response.mcp_servers]
18351833

18361834
return GetMetadataResponse(
18371835
application_id=response.id,

examples/mcp/mcp_tool_discovery.py

Lines changed: 23 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -58,18 +58,18 @@ def main():
5858
print("Connecting to MCPServer 'weather'...")
5959

6060
client = DaprMCPClient(timeout_in_seconds=30)
61-
client.connect("weather")
61+
client.connect('weather')
6262

6363
tools = client.get_all_tools()
64-
print(f"\nDiscovered {len(tools)} tool(s):\n")
64+
print(f'\nDiscovered {len(tools)} tool(s):\n')
6565
for tool in tools:
66-
print(f" Name: {tool.name}")
67-
print(f" Description: {tool.description}")
68-
print(f" Server: {tool.server_name}")
69-
print(f" Workflow: {tool.call_tool_workflow}")
70-
if tool.input_schema.get("properties"):
71-
props = list(tool.input_schema["properties"].keys())
72-
print(f" Parameters: {', '.join(props)}")
66+
print(f' Name: {tool.name}')
67+
print(f' Description: {tool.description}')
68+
print(f' Server: {tool.server_name}')
69+
print(f' Workflow: {tool.call_tool_workflow}')
70+
if tool.input_schema.get('properties'):
71+
props = list(tool.input_schema['properties'].keys())
72+
print(f' Parameters: {", ".join(props)}')
7373
print()
7474

7575
# ------------------------------------------------------------------
@@ -78,35 +78,33 @@ def main():
7878
# durable tool calls via child workflows.
7979
# ------------------------------------------------------------------
8080
if not tools:
81-
print("No tools discovered — exiting.")
81+
print('No tools discovered — exiting.')
8282
return
8383

8484
tool = tools[0]
8585
print(f"Using tool '{tool.name}' in a workflow...\n")
8686

8787
# Build a Pydantic model from the tool's JSON Schema for validation.
8888
if tool.input_schema:
89-
ArgsModel = create_pydantic_model_from_schema(
90-
tool.input_schema, f"{tool.name}Args"
91-
)
92-
print(f" Args model: {ArgsModel.__name__}")
93-
print(f" Fields: {list(ArgsModel.model_fields.keys())}\n")
89+
ArgsModel = create_pydantic_model_from_schema(tool.input_schema, f'{tool.name}Args')
90+
print(f' Args model: {ArgsModel.__name__}')
91+
print(f' Fields: {list(ArgsModel.model_fields.keys())}\n')
9492

9593
# Define a simple workflow that calls the MCP tool.
9694
def call_mcp_tool_workflow(ctx: DaprWorkflowContext, input: dict):
9795
"""Workflow that calls an MCP tool as a child workflow."""
9896
result = yield ctx.call_child_workflow(
9997
workflow=tool.call_tool_workflow,
10098
input={
101-
"toolName": tool.name,
102-
"arguments": input.get("arguments", {}),
99+
'toolName': tool.name,
100+
'arguments': input.get('arguments', {}),
103101
},
104102
)
105103
return result
106104

107105
def print_result(ctx: WorkflowActivityContext, input):
108106
"""Activity that prints the tool result."""
109-
print(f" Tool result: {input}")
107+
print(f' Tool result: {input}')
110108

111109
# Register and run the workflow.
112110
wfr = WorkflowRuntime()
@@ -117,9 +115,9 @@ def print_result(ctx: WorkflowActivityContext, input):
117115
wf_client = DaprWorkflowClient()
118116
instance_id = wf_client.schedule_new_workflow(
119117
workflow=call_mcp_tool_workflow,
120-
input={"arguments": {"location": "Seattle"}},
118+
input={'arguments': {'location': 'Seattle'}},
121119
)
122-
print(f" Scheduled workflow: {instance_id}")
120+
print(f' Scheduled workflow: {instance_id}')
123121

124122
state = wf_client.wait_for_workflow_completion(
125123
instance_id=instance_id,
@@ -128,14 +126,14 @@ def print_result(ctx: WorkflowActivityContext, input):
128126
)
129127

130128
if state:
131-
print(f" Status: {state.runtime_status.name}")
132-
print(f" Output: {state.serialized_output}")
129+
print(f' Status: {state.runtime_status.name}')
130+
print(f' Output: {state.serialized_output}')
133131
else:
134-
print(" Workflow timed out.")
132+
print(' Workflow timed out.')
135133

136134
wfr.shutdown()
137-
print("\nDone.")
135+
print('\nDone.')
138136

139137

140-
if __name__ == "__main__":
138+
if __name__ == '__main__':
141139
main()

examples/mcp/weather_mcp_server.py

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,12 @@
2929

3030
from mcp.server.fastmcp import FastMCP
3131

32-
logging.basicConfig(
33-
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
34-
)
35-
logger = logging.getLogger("weather-mcp-server")
32+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
33+
logger = logging.getLogger('weather-mcp-server')
3634

3735

3836
def build_server(host: str, port: int) -> FastMCP:
39-
mcp = FastMCP("WeatherService", host=host, port=port)
37+
mcp = FastMCP('WeatherService', host=host, port=port)
4038

4139
@mcp.tool()
4240
async def get_weather(location: str) -> str:
@@ -50,10 +48,10 @@ async def get_weather(location: str) -> str:
5048
"""
5149
temperature = random.randint(32, 105)
5250
conditions = random.choice(
53-
["sunny", "cloudy", "partly cloudy", "rainy", "windy", "snowy", "foggy"]
51+
['sunny', 'cloudy', 'partly cloudy', 'rainy', 'windy', 'snowy', 'foggy']
5452
)
5553
humidity = random.randint(20, 95)
56-
return f"{location}: {temperature}F, {conditions}, {humidity}% humidity."
54+
return f'{location}: {temperature}F, {conditions}, {humidity}% humidity.'
5755

5856
@mcp.tool()
5957
async def get_forecast(location: str, days: int = 5) -> str:
@@ -67,36 +65,30 @@ async def get_forecast(location: str, days: int = 5) -> str:
6765
Multi-line forecast summary.
6866
"""
6967
days = min(max(days, 1), 10)
70-
lines = [f"{location} {days}-day forecast:"]
68+
lines = [f'{location} {days}-day forecast:']
7169
for i in range(1, days + 1):
7270
high = random.randint(55, 105)
7371
low = high - random.randint(10, 25)
74-
cond = random.choice(
75-
["sunny", "cloudy", "rainy", "stormy", "clear", "partly cloudy"]
76-
)
77-
lines.append(f" Day {i}: High {high}F / Low {low}F, {cond}")
78-
return "\n".join(lines)
72+
cond = random.choice(['sunny', 'cloudy', 'rainy', 'stormy', 'clear', 'partly cloudy'])
73+
lines.append(f' Day {i}: High {high}F / Low {low}F, {cond}')
74+
return '\n'.join(lines)
7975

8076
return mcp
8177

8278

8379
def main() -> None:
84-
parser = argparse.ArgumentParser(
85-
description="Weather MCP server (streamable-HTTP transport)"
86-
)
87-
parser.add_argument("--host", default="0.0.0.0")
88-
parser.add_argument("--port", type=int, default=8081)
80+
parser = argparse.ArgumentParser(description='Weather MCP server (streamable-HTTP transport)')
81+
parser.add_argument('--host', default='0.0.0.0')
82+
parser.add_argument('--port', type=int, default=8081)
8983
args = parser.parse_args()
9084

9185
mcp = build_server(args.host, args.port)
92-
logger.info(
93-
"Weather MCP server listening on http://%s:%d/mcp", args.host, args.port
94-
)
86+
logger.info('Weather MCP server listening on http://%s:%d/mcp', args.host, args.port)
9587
try:
96-
mcp.run(transport="streamable-http")
88+
mcp.run(transport='streamable-http')
9789
except (KeyboardInterrupt, SystemExit):
98-
logger.info("Shutting down.")
90+
logger.info('Shutting down.')
9991

10092

101-
if __name__ == "__main__":
93+
if __name__ == '__main__':
10294
main()

ext/dapr-ext-workflow/dapr/ext/workflow/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,15 @@
1717
from dapr.ext.workflow._durabletask.task import TaskFailedError
1818
from dapr.ext.workflow.dapr_workflow_client import DaprWorkflowClient
1919
from dapr.ext.workflow.dapr_workflow_context import DaprWorkflowContext, when_all, when_any
20+
21+
# MCP
22+
from dapr.ext.workflow.mcp import MCP_WORKFLOW_PREFIX, DaprMCPClient, MCPToolDef
23+
from dapr.ext.workflow.mcp_schema import create_pydantic_model_from_schema
2024
from dapr.ext.workflow.retry_policy import RetryPolicy
2125
from dapr.ext.workflow.workflow_activity_context import WorkflowActivityContext
2226
from dapr.ext.workflow.workflow_runtime import WorkflowRuntime, alternate_name
2327
from dapr.ext.workflow.workflow_state import WorkflowState, WorkflowStatus
2428

25-
# MCP
26-
from dapr.ext.workflow.mcp import DaprMCPClient, MCPToolDef, MCP_WORKFLOW_PREFIX
27-
from dapr.ext.workflow.mcp_schema import create_pydantic_model_from_schema
28-
2929
__all__ = [
3030
'WorkflowRuntime',
3131
'DaprWorkflowClient',

ext/dapr-ext-workflow/dapr/ext/workflow/aio/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@
1313
limitations under the License.
1414
"""
1515

16-
from .dapr_workflow_client import DaprWorkflowClient
17-
from .mcp import DaprMCPClient
18-
1916
# Re-export MCPToolDef so async users don't need to import from the sync module.
2017
from dapr.ext.workflow.mcp import MCPToolDef
2118

19+
from .dapr_workflow_client import DaprWorkflowClient
20+
from .mcp import DaprMCPClient
21+
2222
__all__ = [
2323
'DaprWorkflowClient',
2424
'DaprMCPClient',

ext/dapr-ext-workflow/dapr/ext/workflow/aio/mcp.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,16 @@
1111
# See the License for the specific language governing permissions and
1212
# limitations under the License.
1313

14-
from __future__ import annotations
15-
1614
"""Async variant of :class:`~dapr.ext.workflow.mcp.DaprMCPClient`."""
1715

16+
from __future__ import annotations
17+
1818
import logging
1919
import uuid
2020
from typing import Optional, Set
2121

2222
from dapr.ext.workflow.aio.dapr_workflow_client import DaprWorkflowClient
23-
from dapr.ext.workflow.mcp import MCP_WORKFLOW_PREFIX, _DaprMCPClientBase, _MCP_METHOD_LIST_TOOLS
23+
from dapr.ext.workflow.mcp import _MCP_METHOD_LIST_TOOLS, MCP_WORKFLOW_PREFIX, _DaprMCPClientBase
2424
from dapr.ext.workflow.workflow_state import WorkflowStatus
2525

2626
logger = logging.getLogger(__name__)
@@ -76,19 +76,17 @@ async def connect(self, mcpserver_name: str) -> None:
7676
ValueError: If *mcpserver_name* is empty.
7777
"""
7878
if not mcpserver_name or not mcpserver_name.strip():
79-
raise ValueError("mcpserver_name must be a non-empty string")
79+
raise ValueError('mcpserver_name must be a non-empty string')
8080

8181
instance_id = str(uuid.uuid4())
8282
# TODO(@sicoyle): reminder to add a func like I have in durabletask-go to use for here instead of building like this!
83-
workflow_name = f"{MCP_WORKFLOW_PREFIX}{mcpserver_name}{_MCP_METHOD_LIST_TOOLS}"
83+
workflow_name = f'{MCP_WORKFLOW_PREFIX}{mcpserver_name}{_MCP_METHOD_LIST_TOOLS}'
8484

85-
logger.debug(
86-
"Scheduling %s (instance=%s)", workflow_name, instance_id
87-
)
85+
logger.debug('Scheduling %s (instance=%s)', workflow_name, instance_id)
8886

8987
await self._wf_client.schedule_new_workflow(
9088
workflow=workflow_name,
91-
input={"mcpServerName": mcpserver_name},
89+
input={'mcpServerName': mcpserver_name},
9290
instance_id=instance_id,
9391
)
9492

@@ -101,14 +99,14 @@ async def connect(self, mcpserver_name: str) -> None:
10199
if state is None:
102100
raise RuntimeError(
103101
f"ListTools workflow for MCPServer '{mcpserver_name}' "
104-
f"timed out after {self._timeout}s"
102+
f'timed out after {self._timeout}s'
105103
)
106104

107105
if state.runtime_status != WorkflowStatus.COMPLETED:
108106
raise RuntimeError(
109107
f"ListTools workflow for MCPServer '{mcpserver_name}' "
110-
f"ended with status {state.runtime_status.name!r}: "
111-
f"{state.serialized_output or ''}"
108+
f'ended with status {state.runtime_status.name!r}: '
109+
f'{state.serialized_output or ""}'
112110
)
113111

114112
self._process_list_tools_result(mcpserver_name, state.serialized_output)

0 commit comments

Comments
 (0)