Jeremiah Lowin commited on
Commit
df2fdf0
·
unverified ·
2 Parent(s): fa7502334f4ddd

Merge branch 'main' into codex/add-agents-md-file

Browse files
docs/deployment/cli.mdx CHANGED
@@ -27,7 +27,7 @@ fastmcp --help
27
 
28
  ### `run`
29
 
30
- Run a FastMCP server directly.
31
 
32
  ```bash
33
  fastmcp run server.py
@@ -47,13 +47,15 @@ This command runs the server directly in your current Python environment. You ar
47
  | Log Level | `--log-level`, `-l` | Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL) |
48
 
49
  #### Server Specification
 
50
 
51
- The server can be specified in two ways:
52
  1. `server.py` - imports the module and looks for a FastMCP object named `mcp`, `server`, or `app`. Errors if no such object is found.
53
  2. `server.py:custom_name` - imports and uses the specified server object
 
54
 
55
  <Tip>
56
- When using `fastmcp run`, it **ignores** the `if __name__ == "__main__"` block entirely. Instead, it finds your server object and calls its `run()` method directly with the transport options you specify. This means you can use `fastmcp run` to override the transport specified in your code.
57
  </Tip>
58
 
59
  For example, if your code contains:
@@ -79,11 +81,17 @@ You can run it with Streamable HTTP transport regardless of what's in the `__mai
79
  fastmcp run server.py --transport streamable-http --port 8000
80
  ```
81
 
82
- **Example**
83
 
84
  ```bash
85
- # Run a server with Streamable HTTP transport on a custom port
86
  fastmcp run server.py --transport streamable-http --port 8000
 
 
 
 
 
 
87
  ```
88
 
89
  ### `dev`
 
27
 
28
  ### `run`
29
 
30
+ Run a FastMCP server directly or proxy a remote server.
31
 
32
  ```bash
33
  fastmcp run server.py
 
47
  | Log Level | `--log-level`, `-l` | Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL) |
48
 
49
  #### Server Specification
50
+ <VersionBadge version="2.4.0" />
51
 
52
+ The server can be specified in three ways:
53
  1. `server.py` - imports the module and looks for a FastMCP object named `mcp`, `server`, or `app`. Errors if no such object is found.
54
  2. `server.py:custom_name` - imports and uses the specified server object
55
+ 3. `http://server-url/path` or `https://server-url/path` - connects to a remote server and creates a proxy
56
 
57
  <Tip>
58
+ When using `fastmcp run` with a local file, it **ignores** the `if __name__ == "__main__"` block entirely. Instead, it finds your server object and calls its `run()` method directly with the transport options you specify. This means you can use `fastmcp run` to override the transport specified in your code.
59
  </Tip>
60
 
61
  For example, if your code contains:
 
81
  fastmcp run server.py --transport streamable-http --port 8000
82
  ```
83
 
84
+ **Examples**
85
 
86
  ```bash
87
+ # Run a local server with Streamable HTTP transport on a custom port
88
  fastmcp run server.py --transport streamable-http --port 8000
89
+
90
+ # Connect to a remote server and proxy as a stdio server
91
+ fastmcp run https://example.com/mcp-server
92
+
93
+ # Connect to a remote server with specified log level
94
+ fastmcp run https://example.com/mcp-server --log-level DEBUG
95
  ```
96
 
97
  ### `dev`
src/fastmcp/cli/cli.py CHANGED
@@ -17,6 +17,7 @@ from typer import Context, Exit
17
 
18
  import fastmcp
19
  from fastmcp.cli import claude
 
20
  from fastmcp.utilities.logging import get_logger
21
 
22
  logger = get_logger("cli")
@@ -58,7 +59,7 @@ def _parse_env_var(env_var: str) -> tuple[str, str]:
58
 
59
 
60
  def _build_uv_command(
61
- file_spec: str,
62
  with_editable: Path | None = None,
63
  with_packages: list[str] | None = None,
64
  ) -> list[str]:
@@ -76,106 +77,10 @@ def _build_uv_command(
76
  cmd.extend(["--with", pkg])
77
 
78
  # Add mcp run command
79
- cmd.extend(["fastmcp", "run", file_spec])
80
  return cmd
81
 
82
 
83
- def _parse_file_path(file_spec: str) -> tuple[Path, str | None]:
84
- """Parse a file path that may include a server object specification.
85
-
86
- Args:
87
- file_spec: Path to file, optionally with :object suffix
88
-
89
- Returns:
90
- Tuple of (file_path, server_object)
91
- """
92
- # First check if we have a Windows path (e.g., C:\...)
93
- has_windows_drive = len(file_spec) > 1 and file_spec[1] == ":"
94
-
95
- # Split on the last colon, but only if it's not part of the Windows drive letter
96
- # and there's actually another colon in the string after the drive letter
97
- if ":" in (file_spec[2:] if has_windows_drive else file_spec):
98
- file_str, server_object = file_spec.rsplit(":", 1)
99
- else:
100
- file_str, server_object = file_spec, None
101
-
102
- # Resolve the file path
103
- file_path = Path(file_str).expanduser().resolve()
104
- if not file_path.exists():
105
- logger.error(f"File not found: {file_path}")
106
- sys.exit(1)
107
- if not file_path.is_file():
108
- logger.error(f"Not a file: {file_path}")
109
- sys.exit(1)
110
-
111
- return file_path, server_object
112
-
113
-
114
- def _import_server(file: Path, server_object: str | None = None):
115
- """Import a MCP server from a file.
116
-
117
- Args:
118
- file: Path to the file
119
- server_object: Optional object name in format "module:object" or just "object"
120
-
121
- Returns:
122
- The server object
123
- """
124
- # Add parent directory to Python path so imports can be resolved
125
- file_dir = str(file.parent)
126
- if file_dir not in sys.path:
127
- sys.path.insert(0, file_dir)
128
-
129
- # Import the module
130
- spec = importlib.util.spec_from_file_location("server_module", file)
131
- if not spec or not spec.loader:
132
- logger.error("Could not load module", extra={"file": str(file)})
133
- sys.exit(1)
134
-
135
- module = importlib.util.module_from_spec(spec)
136
- spec.loader.exec_module(module)
137
-
138
- # If no object specified, try common server names
139
- if not server_object:
140
- # Look for the most common server object names
141
- for name in ["mcp", "server", "app"]:
142
- if hasattr(module, name):
143
- return getattr(module, name)
144
-
145
- logger.error(
146
- f"No server object found in {file}. Please either:\n"
147
- "1. Use a standard variable name (mcp, server, or app)\n"
148
- "2. Specify the object name with file:object syntax",
149
- extra={"file": str(file)},
150
- )
151
- sys.exit(1)
152
-
153
- # Handle module:object syntax
154
- if ":" in server_object:
155
- module_name, object_name = server_object.split(":", 1)
156
- try:
157
- server_module = importlib.import_module(module_name)
158
- server = getattr(server_module, object_name, None)
159
- except ImportError:
160
- logger.error(
161
- f"Could not import module '{module_name}'",
162
- extra={"file": str(file)},
163
- )
164
- sys.exit(1)
165
- else:
166
- # Just object name
167
- server = getattr(module, server_object, None)
168
-
169
- if server is None:
170
- logger.error(
171
- f"Server object '{server_object}' not found",
172
- extra={"file": str(file)},
173
- )
174
- sys.exit(1)
175
-
176
- return server
177
-
178
-
179
  @app.command()
180
  def version(ctx: Context):
181
  if ctx.resilient_parsing:
@@ -201,7 +106,7 @@ def version(ctx: Context):
201
 
202
  @app.command()
203
  def dev(
204
- file_spec: str = typer.Argument(
205
  ...,
206
  help="Python file to run, optionally with :object suffix",
207
  ),
@@ -246,7 +151,7 @@ def dev(
246
  ] = None,
247
  ) -> None:
248
  """Run a MCP server with the MCP Inspector."""
249
- file, server_object = _parse_file_path(file_spec)
250
 
251
  logger.debug(
252
  "Starting dev server",
@@ -262,7 +167,7 @@ def dev(
262
 
263
  try:
264
  # Import server to get dependencies
265
- server = _import_server(file, server_object)
266
  if hasattr(server, "dependencies") and server.dependencies is not None:
267
  with_packages = list(set(with_packages + server.dependencies))
268
 
@@ -285,7 +190,7 @@ def dev(
285
  if inspector_version:
286
  inspector_cmd += f"@{inspector_version}"
287
 
288
- uv_cmd = _build_uv_command(file_spec, with_editable, with_packages)
289
 
290
  # Run the MCP Inspector command with shell=True on Windows
291
  shell = sys.platform == "win32"
@@ -318,9 +223,9 @@ def dev(
318
 
319
  @app.command()
320
  def run(
321
- file_spec: str = typer.Argument(
322
  ...,
323
- help="Python file to run, optionally with :object suffix",
324
  ),
325
  transport: Annotated[
326
  str | None,
@@ -354,22 +259,20 @@ def run(
354
  ),
355
  ] = None,
356
  ) -> None:
357
- """Run a MCP server.
358
 
359
- The server can be specified in two ways:
360
- 1. Module approach: server.py - runs the module directly, expecting a server.run() call.\n
361
- 2. Import approach: server.py:app - imports and runs the specified server object.\n\n
 
362
 
363
  Note: This command runs the server directly. You are responsible for ensuring
364
  all dependencies are available.
365
  """
366
- file, server_object = _parse_file_path(file_spec)
367
-
368
  logger.debug(
369
- "Running server",
370
  extra={
371
- "file": str(file),
372
- "server_object": server_object,
373
  "transport": transport,
374
  "host": host,
375
  "port": port,
@@ -378,29 +281,18 @@ def run(
378
  )
379
 
380
  try:
381
- # Import and get server object
382
- server = _import_server(file, server_object)
383
-
384
- logger.info(f'Found server "{server.name}" in {file}')
385
-
386
- # Run the server
387
- kwargs = {}
388
- if transport:
389
- kwargs["transport"] = transport
390
- if host:
391
- kwargs["host"] = host
392
- if port:
393
- kwargs["port"] = port
394
- if log_level:
395
- kwargs["log_level"] = log_level
396
-
397
- server.run(**kwargs)
398
-
399
  except Exception as e:
400
  logger.error(
401
- f"Failed to run server: {e}",
402
  extra={
403
- "file": str(file),
404
  "error": str(e),
405
  },
406
  )
@@ -409,7 +301,7 @@ def run(
409
 
410
  @app.command()
411
  def install(
412
- file_spec: str = typer.Argument(
413
  ...,
414
  help="Python file to run, optionally with :object suffix",
415
  ),
@@ -466,7 +358,7 @@ def install(
466
  Environment variables are preserved once added and only updated if new values
467
  are explicitly provided.
468
  """
469
- file, server_object = _parse_file_path(file_spec)
470
 
471
  logger.debug(
472
  "Installing server",
@@ -489,7 +381,7 @@ def install(
489
  server = None
490
  if not name:
491
  try:
492
- server = _import_server(file, server_object)
493
  name = server.name
494
  except (ImportError, ModuleNotFoundError) as e:
495
  logger.debug(
@@ -526,7 +418,7 @@ def install(
526
  env_dict[key] = value
527
 
528
  if claude.update_claude_config(
529
- file_spec,
530
  name,
531
  with_editable=with_editable,
532
  with_packages=with_packages,
 
17
 
18
  import fastmcp
19
  from fastmcp.cli import claude
20
+ from fastmcp.cli import run as run_module
21
  from fastmcp.utilities.logging import get_logger
22
 
23
  logger = get_logger("cli")
 
59
 
60
 
61
  def _build_uv_command(
62
+ server_spec: str,
63
  with_editable: Path | None = None,
64
  with_packages: list[str] | None = None,
65
  ) -> list[str]:
 
77
  cmd.extend(["--with", pkg])
78
 
79
  # Add mcp run command
80
+ cmd.extend(["fastmcp", "run", server_spec])
81
  return cmd
82
 
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  @app.command()
85
  def version(ctx: Context):
86
  if ctx.resilient_parsing:
 
106
 
107
  @app.command()
108
  def dev(
109
+ server_spec: str = typer.Argument(
110
  ...,
111
  help="Python file to run, optionally with :object suffix",
112
  ),
 
151
  ] = None,
152
  ) -> None:
153
  """Run a MCP server with the MCP Inspector."""
154
+ file, server_object = run_module.parse_file_path(server_spec)
155
 
156
  logger.debug(
157
  "Starting dev server",
 
167
 
168
  try:
169
  # Import server to get dependencies
170
+ server = run_module.import_server(file, server_object)
171
  if hasattr(server, "dependencies") and server.dependencies is not None:
172
  with_packages = list(set(with_packages + server.dependencies))
173
 
 
190
  if inspector_version:
191
  inspector_cmd += f"@{inspector_version}"
192
 
193
+ uv_cmd = _build_uv_command(server_spec, with_editable, with_packages)
194
 
195
  # Run the MCP Inspector command with shell=True on Windows
196
  shell = sys.platform == "win32"
 
223
 
224
  @app.command()
225
  def run(
226
+ server_spec: str = typer.Argument(
227
  ...,
228
+ help="Python file, object specification (file:obj), or URL",
229
  ),
230
  transport: Annotated[
231
  str | None,
 
259
  ),
260
  ] = None,
261
  ) -> None:
262
+ """Run a MCP server or connect to a remote one.
263
 
264
+ The server can be specified in three ways:
265
+ 1. Module approach: server.py - runs the module directly, looking for an object named mcp/server/app.\n
266
+ 2. Import approach: server.py:app - imports and runs the specified server object.\n
267
+ 3. URL approach: http://server-url - connects to a remote server and creates a proxy.\n\n
268
 
269
  Note: This command runs the server directly. You are responsible for ensuring
270
  all dependencies are available.
271
  """
 
 
272
  logger.debug(
273
+ "Running server or client",
274
  extra={
275
+ "server_spec": server_spec,
 
276
  "transport": transport,
277
  "host": host,
278
  "port": port,
 
281
  )
282
 
283
  try:
284
+ run_module.run_command(
285
+ server_spec=server_spec,
286
+ transport=transport,
287
+ host=host,
288
+ port=port,
289
+ log_level=log_level,
290
+ )
 
 
 
 
 
 
 
 
 
 
 
291
  except Exception as e:
292
  logger.error(
293
+ f"Failed to run: {e}",
294
  extra={
295
+ "server_spec": server_spec,
296
  "error": str(e),
297
  },
298
  )
 
301
 
302
  @app.command()
303
  def install(
304
+ server_spec: str = typer.Argument(
305
  ...,
306
  help="Python file to run, optionally with :object suffix",
307
  ),
 
358
  Environment variables are preserved once added and only updated if new values
359
  are explicitly provided.
360
  """
361
+ file, server_object = run_module.parse_file_path(server_spec)
362
 
363
  logger.debug(
364
  "Installing server",
 
381
  server = None
382
  if not name:
383
  try:
384
+ server = run_module.import_server(file, server_object)
385
  name = server.name
386
  except (ImportError, ModuleNotFoundError) as e:
387
  logger.debug(
 
418
  env_dict[key] = value
419
 
420
  if claude.update_claude_config(
421
+ server_spec,
422
  name,
423
  with_editable=with_editable,
424
  with_packages=with_packages,
src/fastmcp/cli/run.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastMCP run command implementation."""
2
+
3
+ import importlib.util
4
+ import re
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+
9
+ from fastmcp.utilities.logging import get_logger
10
+
11
+ logger = get_logger("cli.run")
12
+
13
+ TransportType = Literal["stdio", "streamable-http", "sse"]
14
+
15
+
16
+ def is_url(path: str) -> bool:
17
+ """Check if a string is a URL."""
18
+ url_pattern = re.compile(r"^https?://")
19
+ return bool(url_pattern.match(path))
20
+
21
+
22
+ def parse_file_path(server_spec: str) -> tuple[Path, str | None]:
23
+ """Parse a file path that may include a server object specification.
24
+
25
+ Args:
26
+ server_spec: Path to file, optionally with :object suffix
27
+
28
+ Returns:
29
+ Tuple of (file_path, server_object)
30
+ """
31
+ # First check if we have a Windows path (e.g., C:\...)
32
+ has_windows_drive = len(server_spec) > 1 and server_spec[1] == ":"
33
+
34
+ # Split on the last colon, but only if it's not part of the Windows drive letter
35
+ # and there's actually another colon in the string after the drive letter
36
+ if ":" in (server_spec[2:] if has_windows_drive else server_spec):
37
+ file_str, server_object = server_spec.rsplit(":", 1)
38
+ else:
39
+ file_str, server_object = server_spec, None
40
+
41
+ # Resolve the file path
42
+ file_path = Path(file_str).expanduser().resolve()
43
+ if not file_path.exists():
44
+ logger.error(f"File not found: {file_path}")
45
+ sys.exit(1)
46
+ if not file_path.is_file():
47
+ logger.error(f"Not a file: {file_path}")
48
+ sys.exit(1)
49
+
50
+ return file_path, server_object
51
+
52
+
53
+ def import_server(file: Path, server_object: str | None = None) -> Any:
54
+ """Import a MCP server from a file.
55
+
56
+ Args:
57
+ file: Path to the file
58
+ server_object: Optional object name in format "module:object" or just "object"
59
+
60
+ Returns:
61
+ The server object
62
+ """
63
+ # Add parent directory to Python path so imports can be resolved
64
+ file_dir = str(file.parent)
65
+ if file_dir not in sys.path:
66
+ sys.path.insert(0, file_dir)
67
+
68
+ # Import the module
69
+ spec = importlib.util.spec_from_file_location("server_module", file)
70
+ if not spec or not spec.loader:
71
+ logger.error("Could not load module", extra={"file": str(file)})
72
+ sys.exit(1)
73
+
74
+ module = importlib.util.module_from_spec(spec)
75
+ spec.loader.exec_module(module)
76
+
77
+ # If no object specified, try common server names
78
+ if not server_object:
79
+ # Look for the most common server object names
80
+ for name in ["mcp", "server", "app"]:
81
+ if hasattr(module, name):
82
+ return getattr(module, name)
83
+
84
+ logger.error(
85
+ f"No server object found in {file}. Please either:\n"
86
+ "1. Use a standard variable name (mcp, server, or app)\n"
87
+ "2. Specify the object name with file:object syntax",
88
+ extra={"file": str(file)},
89
+ )
90
+ sys.exit(1)
91
+
92
+ # Handle module:object syntax
93
+ if ":" in server_object:
94
+ module_name, object_name = server_object.split(":", 1)
95
+ try:
96
+ server_module = importlib.import_module(module_name)
97
+ server = getattr(server_module, object_name, None)
98
+ except ImportError:
99
+ logger.error(
100
+ f"Could not import module '{module_name}'",
101
+ extra={"file": str(file)},
102
+ )
103
+ sys.exit(1)
104
+ else:
105
+ # Just object name
106
+ server = getattr(module, server_object, None)
107
+
108
+ if server is None:
109
+ logger.error(
110
+ f"Server object '{server_object}' not found",
111
+ extra={"file": str(file)},
112
+ )
113
+ sys.exit(1)
114
+
115
+ return server
116
+
117
+
118
+ def create_client_server(url: str) -> Any:
119
+ """Create a FastMCP server from a client URL.
120
+
121
+ Args:
122
+ url: The URL to connect to
123
+
124
+ Returns:
125
+ A FastMCP server instance
126
+ """
127
+ try:
128
+ import fastmcp
129
+
130
+ client = fastmcp.Client(url)
131
+ server = fastmcp.FastMCP.from_client(client)
132
+ return server
133
+ except Exception as e:
134
+ logger.error(f"Failed to create client for URL {url}: {e}")
135
+ sys.exit(1)
136
+
137
+
138
+ def run_command(
139
+ server_spec: str,
140
+ transport: str | None = None,
141
+ host: str | None = None,
142
+ port: int | None = None,
143
+ log_level: str | None = None,
144
+ ) -> None:
145
+ """Run a MCP server or connect to a remote one.
146
+
147
+ Args:
148
+ server_spec: Python file, object specification (file:obj), or URL
149
+ transport: Transport protocol to use
150
+ host: Host to bind to when using http transport
151
+ port: Port to bind to when using http transport
152
+ log_level: Log level
153
+ """
154
+ if is_url(server_spec):
155
+ # Handle URL case
156
+ server = create_client_server(server_spec)
157
+ logger.debug(f"Created client proxy server for {server_spec}")
158
+ else:
159
+ # Handle file case
160
+ file, server_object = parse_file_path(server_spec)
161
+ server = import_server(file, server_object)
162
+ logger.debug(f'Found server "{server.name}" in {file}')
163
+
164
+ # Run the server
165
+ kwargs = {}
166
+ if transport:
167
+ kwargs["transport"] = transport
168
+ if host:
169
+ kwargs["host"] = host
170
+ if port:
171
+ kwargs["port"] = port
172
+ if log_level:
173
+ kwargs["log_level"] = log_level
174
+
175
+ try:
176
+ server.run(**kwargs)
177
+ except Exception as e:
178
+ logger.error(f"Failed to run server: {e}")
179
+ sys.exit(1)
src/fastmcp/server/http.py CHANGED
@@ -254,6 +254,7 @@ def create_sse_app(
254
  )
255
  # Store the FastMCP server instance on the Starlette app state
256
  app.state.fastmcp_server = server
 
257
 
258
  return app
259
 
@@ -357,4 +358,6 @@ def create_streamable_http_app(
357
  # Store the FastMCP server instance on the Starlette app state
358
  app.state.fastmcp_server = server
359
 
 
 
360
  return app
 
254
  )
255
  # Store the FastMCP server instance on the Starlette app state
256
  app.state.fastmcp_server = server
257
+ app.state.path = sse_path
258
 
259
  return app
260
 
 
358
  # Store the FastMCP server instance on the Starlette app state
359
  app.state.fastmcp_server = server
360
 
361
+ app.state.path = streamable_http_path
362
+
363
  return app
src/fastmcp/server/server.py CHANGED
@@ -213,7 +213,6 @@ class FastMCP(Generic[LifespanResultT]):
213
  Args:
214
  transport: Transport protocol to use ("stdio", "sse", or "streamable-http")
215
  """
216
- logger.info(f'Starting server "{self.name}"...')
217
 
218
  anyio.run(partial(self.run_async, transport, **transport_kwargs))
219
 
@@ -730,6 +729,7 @@ class FastMCP(Generic[LifespanResultT]):
730
  async def run_stdio_async(self) -> None:
731
  """Run the server using stdio transport."""
732
  async with stdio_server() as (read_stream, write_stream):
 
733
  await self._mcp_server.run(
734
  read_stream,
735
  write_stream,
@@ -763,16 +763,24 @@ class FastMCP(Generic[LifespanResultT]):
763
  # lifespan is required for streamable http
764
  uvicorn_config["lifespan"] = "on"
765
 
 
 
 
 
766
  app = self.http_app(path=path, transport=transport, middleware=middleware)
767
 
768
  config = uvicorn.Config(
769
  app,
770
- host=host or self.settings.host,
771
- port=port or self.settings.port,
772
- log_level=log_level or self.settings.log_level.lower(),
773
  **uvicorn_config,
774
  )
775
  server = uvicorn.Server(config)
 
 
 
 
776
  await server.serve()
777
 
778
  async def run_sse_async(
 
213
  Args:
214
  transport: Transport protocol to use ("stdio", "sse", or "streamable-http")
215
  """
 
216
 
217
  anyio.run(partial(self.run_async, transport, **transport_kwargs))
218
 
 
729
  async def run_stdio_async(self) -> None:
730
  """Run the server using stdio transport."""
731
  async with stdio_server() as (read_stream, write_stream):
732
+ logger.info(f"Starting MCP server {self.name!r} with transport 'stdio'")
733
  await self._mcp_server.run(
734
  read_stream,
735
  write_stream,
 
763
  # lifespan is required for streamable http
764
  uvicorn_config["lifespan"] = "on"
765
 
766
+ host = host or self.settings.host
767
+ port = port or self.settings.port
768
+ log_level = log_level or self.settings.log_level.lower()
769
+
770
  app = self.http_app(path=path, transport=transport, middleware=middleware)
771
 
772
  config = uvicorn.Config(
773
  app,
774
+ host=host,
775
+ port=port,
776
+ log_level=log_level,
777
  **uvicorn_config,
778
  )
779
  server = uvicorn.Server(config)
780
+ path = app.state.path.lstrip("/") # type: ignore
781
+ logger.info(
782
+ f"Starting MCP server {self.name!r} with transport {transport!r} on http://{host}:{port}/{path}"
783
+ )
784
  await server.serve()
785
 
786
  async def run_sse_async(
tests/cli/test_cli.py CHANGED
@@ -173,74 +173,6 @@ class TestHelperFunctions:
173
  "file.py:server",
174
  ]
175
 
176
- def test_parse_file_path_simple(self):
177
- """Test parsing simple file path."""
178
- with (
179
- patch("pathlib.Path.exists") as mock_exists,
180
- patch("pathlib.Path.is_file") as mock_is_file,
181
- patch("pathlib.Path.expanduser") as mock_expanduser,
182
- patch("pathlib.Path.resolve") as mock_resolve,
183
- ):
184
- mock_exists.return_value = True
185
- mock_is_file.return_value = True
186
- mock_expanduser.return_value = Path("file.py")
187
- mock_resolve.return_value = Path("file.py")
188
-
189
- path, obj = cli._parse_file_path("file.py")
190
- assert path == Path("file.py")
191
- assert obj is None
192
-
193
- def test_parse_file_path_with_object(self):
194
- """Test parsing file path with object."""
195
- with (
196
- patch("pathlib.Path.exists") as mock_exists,
197
- patch("pathlib.Path.is_file") as mock_is_file,
198
- patch("pathlib.Path.expanduser") as mock_expanduser,
199
- patch("pathlib.Path.resolve") as mock_resolve,
200
- ):
201
- mock_exists.return_value = True
202
- mock_is_file.return_value = True
203
- mock_expanduser.return_value = Path("file.py")
204
- mock_resolve.return_value = Path("file.py")
205
-
206
- path, obj = cli._parse_file_path("file.py:server")
207
- assert path == Path("file.py")
208
- assert obj == "server"
209
-
210
- def test_parse_file_path_windows(self):
211
- """Test parsing Windows file path."""
212
- with (
213
- patch("pathlib.Path.exists") as mock_exists,
214
- patch("pathlib.Path.is_file") as mock_is_file,
215
- patch("pathlib.Path.expanduser") as mock_expanduser,
216
- patch("pathlib.Path.resolve") as mock_resolve,
217
- ):
218
- mock_exists.return_value = True
219
- mock_is_file.return_value = True
220
- mock_expanduser.return_value = Path("C:/path/file.py")
221
- mock_resolve.return_value = Path("C:/path/file.py")
222
-
223
- path, obj = cli._parse_file_path("C:/path/file.py:server")
224
- assert path == Path("C:/path/file.py")
225
- assert obj == "server"
226
-
227
- def test_parse_file_path_not_file(self, mock_exit, mock_logger):
228
- """Test parsing path that is not a file."""
229
- with (
230
- patch("pathlib.Path.exists") as mock_exists,
231
- patch("pathlib.Path.is_file") as mock_is_file,
232
- patch("pathlib.Path.expanduser") as mock_expanduser,
233
- patch("pathlib.Path.resolve") as mock_resolve,
234
- ):
235
- mock_exists.return_value = True
236
- mock_is_file.return_value = False
237
- mock_expanduser.return_value = Path("directory")
238
- mock_resolve.return_value = Path("directory")
239
-
240
- cli._parse_file_path("directory")
241
- mock_logger.error.assert_called_once()
242
- mock_exit.assert_called_once_with(1)
243
-
244
 
245
  class TestVersionCommand:
246
  """Tests for the version command."""
@@ -259,8 +191,8 @@ class TestDevCommand:
259
  def test_dev_command_success(self, temp_python_file, mock_logger):
260
  """Test successful dev command execution."""
261
  with (
262
- patch("fastmcp.cli.cli._parse_file_path") as mock_parse,
263
- patch("fastmcp.cli.cli._import_server") as mock_import,
264
  patch("fastmcp.cli.cli._get_npx_command") as mock_get_npx,
265
  patch("fastmcp.cli.cli._build_uv_command") as mock_build_uv,
266
  patch("subprocess.run") as mock_run,
@@ -285,8 +217,8 @@ class TestDevCommand:
285
  def test_dev_command_with_ui_port(self, temp_python_file):
286
  """Test dev command with UI port."""
287
  with (
288
- patch("fastmcp.cli.cli._parse_file_path") as mock_parse,
289
- patch("fastmcp.cli.cli._import_server") as mock_import,
290
  patch("fastmcp.cli.cli._get_npx_command") as mock_get_npx,
291
  patch("fastmcp.cli.cli._build_uv_command") as mock_build_uv,
292
  patch("subprocess.run") as mock_run,
@@ -310,8 +242,8 @@ class TestDevCommand:
310
  def test_dev_command_with_server_port(self, temp_python_file):
311
  """Test dev command with server port."""
312
  with (
313
- patch("fastmcp.cli.cli._parse_file_path") as mock_parse,
314
- patch("fastmcp.cli.cli._import_server") as mock_import,
315
  patch("fastmcp.cli.cli._get_npx_command") as mock_get_npx,
316
  patch("fastmcp.cli.cli._build_uv_command") as mock_build_uv,
317
  patch("subprocess.run") as mock_run,
@@ -335,8 +267,8 @@ class TestDevCommand:
335
  def test_dev_command_inspector_version(self, temp_python_file):
336
  """Test dev command with specific inspector version."""
337
  with (
338
- patch("fastmcp.cli.cli._parse_file_path") as mock_parse,
339
- patch("fastmcp.cli.cli._import_server") as mock_import,
340
  patch("fastmcp.cli.cli._get_npx_command") as mock_get_npx,
341
  patch("fastmcp.cli.cli._build_uv_command") as mock_build_uv,
342
  patch("subprocess.run") as mock_run,
@@ -360,11 +292,12 @@ class TestDevCommand:
360
  class TestRunCommand:
361
  """Tests for the run command."""
362
 
363
- def test_run_command_success(self, temp_python_file, mock_logger):
364
  """Test successful run command execution."""
365
  with (
366
- patch("fastmcp.cli.cli._parse_file_path") as mock_parse,
367
- patch("fastmcp.cli.cli._import_server") as mock_import,
 
368
  ):
369
  mock_parse.return_value = (temp_python_file, None)
370
  mock_server = MagicMock()
@@ -374,15 +307,15 @@ class TestRunCommand:
374
  result = runner.invoke(cli.app, ["run", str(temp_python_file)])
375
  assert result.exit_code == 0
376
  mock_server.run.assert_called_once_with()
377
- mock_logger.info.assert_called_with(
378
  f'Found server "test_server" in {temp_python_file}'
379
  )
380
 
381
  def test_run_command_with_transport(self, temp_python_file):
382
  """Test run command with transport option."""
383
  with (
384
- patch("fastmcp.cli.cli._parse_file_path") as mock_parse,
385
- patch("fastmcp.cli.cli._import_server") as mock_import,
386
  ):
387
  mock_parse.return_value = (temp_python_file, None)
388
  mock_server = MagicMock()
@@ -398,8 +331,8 @@ class TestRunCommand:
398
  def test_run_command_with_host(self, temp_python_file):
399
  """Test run command with host option."""
400
  with (
401
- patch("fastmcp.cli.cli._parse_file_path") as mock_parse,
402
- patch("fastmcp.cli.cli._import_server") as mock_import,
403
  ):
404
  mock_parse.return_value = (temp_python_file, None)
405
  mock_server = MagicMock()
@@ -415,8 +348,8 @@ class TestRunCommand:
415
  def test_run_command_with_port(self, temp_python_file):
416
  """Test run command with port option."""
417
  with (
418
- patch("fastmcp.cli.cli._parse_file_path") as mock_parse,
419
- patch("fastmcp.cli.cli._import_server") as mock_import,
420
  ):
421
  mock_parse.return_value = (temp_python_file, None)
422
  mock_server = MagicMock()
@@ -432,8 +365,8 @@ class TestRunCommand:
432
  def test_run_command_with_log_level(self, temp_python_file):
433
  """Test run command with log level option."""
434
  with (
435
- patch("fastmcp.cli.cli._parse_file_path") as mock_parse,
436
- patch("fastmcp.cli.cli._import_server") as mock_import,
437
  ):
438
  mock_parse.return_value = (temp_python_file, None)
439
  mock_server = MagicMock()
@@ -449,8 +382,8 @@ class TestRunCommand:
449
  def test_run_command_with_multiple_options(self, temp_python_file):
450
  """Test run command with multiple options."""
451
  with (
452
- patch("fastmcp.cli.cli._parse_file_path") as mock_parse,
453
- patch("fastmcp.cli.cli._import_server") as mock_import,
454
  ):
455
  mock_parse.return_value = (temp_python_file, None)
456
  mock_server = MagicMock()
 
173
  "file.py:server",
174
  ]
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
  class TestVersionCommand:
178
  """Tests for the version command."""
 
191
  def test_dev_command_success(self, temp_python_file, mock_logger):
192
  """Test successful dev command execution."""
193
  with (
194
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
195
+ patch("fastmcp.cli.run.import_server") as mock_import,
196
  patch("fastmcp.cli.cli._get_npx_command") as mock_get_npx,
197
  patch("fastmcp.cli.cli._build_uv_command") as mock_build_uv,
198
  patch("subprocess.run") as mock_run,
 
217
  def test_dev_command_with_ui_port(self, temp_python_file):
218
  """Test dev command with UI port."""
219
  with (
220
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
221
+ patch("fastmcp.cli.run.import_server") as mock_import,
222
  patch("fastmcp.cli.cli._get_npx_command") as mock_get_npx,
223
  patch("fastmcp.cli.cli._build_uv_command") as mock_build_uv,
224
  patch("subprocess.run") as mock_run,
 
242
  def test_dev_command_with_server_port(self, temp_python_file):
243
  """Test dev command with server port."""
244
  with (
245
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
246
+ patch("fastmcp.cli.run.import_server") as mock_import,
247
  patch("fastmcp.cli.cli._get_npx_command") as mock_get_npx,
248
  patch("fastmcp.cli.cli._build_uv_command") as mock_build_uv,
249
  patch("subprocess.run") as mock_run,
 
267
  def test_dev_command_inspector_version(self, temp_python_file):
268
  """Test dev command with specific inspector version."""
269
  with (
270
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
271
+ patch("fastmcp.cli.run.import_server") as mock_import,
272
  patch("fastmcp.cli.cli._get_npx_command") as mock_get_npx,
273
  patch("fastmcp.cli.cli._build_uv_command") as mock_build_uv,
274
  patch("subprocess.run") as mock_run,
 
292
  class TestRunCommand:
293
  """Tests for the run command."""
294
 
295
+ def test_run_command_success(self, temp_python_file):
296
  """Test successful run command execution."""
297
  with (
298
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
299
+ patch("fastmcp.cli.run.import_server") as mock_import,
300
+ patch("fastmcp.cli.run.logger") as mock_logger,
301
  ):
302
  mock_parse.return_value = (temp_python_file, None)
303
  mock_server = MagicMock()
 
307
  result = runner.invoke(cli.app, ["run", str(temp_python_file)])
308
  assert result.exit_code == 0
309
  mock_server.run.assert_called_once_with()
310
+ mock_logger.debug.assert_called_with(
311
  f'Found server "test_server" in {temp_python_file}'
312
  )
313
 
314
  def test_run_command_with_transport(self, temp_python_file):
315
  """Test run command with transport option."""
316
  with (
317
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
318
+ patch("fastmcp.cli.run.import_server") as mock_import,
319
  ):
320
  mock_parse.return_value = (temp_python_file, None)
321
  mock_server = MagicMock()
 
331
  def test_run_command_with_host(self, temp_python_file):
332
  """Test run command with host option."""
333
  with (
334
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
335
+ patch("fastmcp.cli.run.import_server") as mock_import,
336
  ):
337
  mock_parse.return_value = (temp_python_file, None)
338
  mock_server = MagicMock()
 
348
  def test_run_command_with_port(self, temp_python_file):
349
  """Test run command with port option."""
350
  with (
351
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
352
+ patch("fastmcp.cli.run.import_server") as mock_import,
353
  ):
354
  mock_parse.return_value = (temp_python_file, None)
355
  mock_server = MagicMock()
 
365
  def test_run_command_with_log_level(self, temp_python_file):
366
  """Test run command with log level option."""
367
  with (
368
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
369
+ patch("fastmcp.cli.run.import_server") as mock_import,
370
  ):
371
  mock_parse.return_value = (temp_python_file, None)
372
  mock_server = MagicMock()
 
382
  def test_run_command_with_multiple_options(self, temp_python_file):
383
  """Test run command with multiple options."""
384
  with (
385
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
386
+ patch("fastmcp.cli.run.import_server") as mock_import,
387
  ):
388
  mock_parse.return_value = (temp_python_file, None)
389
  mock_server = MagicMock()
tests/cli/test_run.py CHANGED
@@ -1,22 +1,262 @@
 
 
 
 
 
1
  import pytest
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
 
4
  @pytest.fixture
5
- def server_file(tmp_path):
6
- """Create a simple server file for testing"""
7
- server_path = tmp_path / "test_server.py"
8
- server_path.write_text(
9
- """
10
- from fastmcp import FastMCP
11
 
12
- mcp = FastMCP(name="TestServer")
13
 
14
- @mcp.tool()
15
- def hello(name: str) -> str:
16
- return f"Hello, {name}!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- if __name__ == "__main__":
19
- mcp.run()
 
 
 
 
 
20
  """
21
- )
22
- return server_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the CLI module."""
2
+
3
+ from pathlib import Path
4
+ from unittest.mock import MagicMock, patch
5
+
6
  import pytest
7
+ from typer.testing import CliRunner
8
+
9
+ import fastmcp.cli.run
10
+ from fastmcp.cli import cli
11
+
12
+ # Set up test runner
13
+ runner = CliRunner()
14
+
15
+
16
+ @pytest.fixture
17
+ def mock_console():
18
+ """Mock the rich console to test output."""
19
+ with patch("fastmcp.cli.cli.console") as mock_console:
20
+ yield mock_console
21
+
22
+
23
+ @pytest.fixture
24
+ def mock_logger():
25
+ """Mock the logger to test logging."""
26
+ with patch("fastmcp.cli.cli.logger") as mock_logger:
27
+ yield mock_logger
28
 
29
 
30
  @pytest.fixture
31
+ def mock_exit():
32
+ """Mock sys.exit to prevent tests from exiting."""
33
+ with patch("sys.exit") as mock_exit:
34
+ yield mock_exit
 
 
35
 
 
36
 
37
+ @pytest.fixture
38
+ def temp_python_file(tmp_path):
39
+ """Create a temporary Python file with a test server."""
40
+ server_code = """
41
+ from mcp import Server
42
+
43
+ class TestServer(Server):
44
+ name = "test_server"
45
+ dependencies = ["package1", "package2"]
46
+
47
+ def run(self, **kwargs):
48
+ print("Running server with", kwargs)
49
+
50
+ mcp = TestServer()
51
+ server = TestServer()
52
+ app = TestServer()
53
+ custom_server = TestServer()
54
+ """
55
+ file_path = tmp_path / "test_server.py"
56
+ file_path.write_text(server_code)
57
+ return file_path
58
 
59
+
60
+ @pytest.fixture
61
+ def temp_env_file(tmp_path):
62
+ """Create a temporary .env file."""
63
+ env_content = """
64
+ TEST_VAR1=value1
65
+ TEST_VAR2=value2
66
  """
67
+ env_path = tmp_path / ".env"
68
+ env_path.write_text(env_content)
69
+ return env_path
70
+
71
+
72
+ class TestHelperFunctions:
73
+ def test_parse_file_path_simple(self):
74
+ """Test parsing simple file path."""
75
+ with (
76
+ patch("pathlib.Path.exists") as mock_exists,
77
+ patch("pathlib.Path.is_file") as mock_is_file,
78
+ patch("pathlib.Path.expanduser") as mock_expanduser,
79
+ patch("pathlib.Path.resolve") as mock_resolve,
80
+ ):
81
+ mock_exists.return_value = True
82
+ mock_is_file.return_value = True
83
+ mock_expanduser.return_value = Path("file.py")
84
+ mock_resolve.return_value = Path("file.py")
85
+
86
+ path, obj = fastmcp.cli.run.parse_file_path("file.py")
87
+ assert path == Path("file.py")
88
+ assert obj is None
89
+
90
+ def test_parse_file_path_with_object(self):
91
+ """Test parsing file path with object."""
92
+ with (
93
+ patch("pathlib.Path.exists") as mock_exists,
94
+ patch("pathlib.Path.is_file") as mock_is_file,
95
+ patch("pathlib.Path.expanduser") as mock_expanduser,
96
+ patch("pathlib.Path.resolve") as mock_resolve,
97
+ ):
98
+ mock_exists.return_value = True
99
+ mock_is_file.return_value = True
100
+ mock_expanduser.return_value = Path("file.py")
101
+ mock_resolve.return_value = Path("file.py")
102
+
103
+ path, obj = fastmcp.cli.run.parse_file_path("file.py:server")
104
+ assert path == Path("file.py")
105
+ assert obj == "server"
106
+
107
+ def test_parse_file_path_windows(self):
108
+ """Test parsing Windows file path."""
109
+ with (
110
+ patch("pathlib.Path.exists") as mock_exists,
111
+ patch("pathlib.Path.is_file") as mock_is_file,
112
+ patch("pathlib.Path.expanduser") as mock_expanduser,
113
+ patch("pathlib.Path.resolve") as mock_resolve,
114
+ ):
115
+ mock_exists.return_value = True
116
+ mock_is_file.return_value = True
117
+ mock_expanduser.return_value = Path("C:/path/file.py")
118
+ mock_resolve.return_value = Path("C:/path/file.py")
119
+
120
+ path, obj = fastmcp.cli.run.parse_file_path("C:/path/file.py:server")
121
+ assert path == Path("C:/path/file.py")
122
+ assert obj == "server"
123
+
124
+ def test_parse_file_path_not_file(self, mock_exit):
125
+ """Test parsing path that is not a file."""
126
+ with (
127
+ patch("pathlib.Path.exists") as mock_exists,
128
+ patch("pathlib.Path.is_file") as mock_is_file,
129
+ patch("pathlib.Path.expanduser") as mock_expanduser,
130
+ patch("pathlib.Path.resolve") as mock_resolve,
131
+ patch("fastmcp.cli.run.logger") as mock_logger,
132
+ ):
133
+ mock_exists.return_value = True
134
+ mock_is_file.return_value = False
135
+ mock_expanduser.return_value = Path("directory")
136
+ mock_resolve.return_value = Path("directory")
137
+
138
+ fastmcp.cli.run.parse_file_path("directory")
139
+ mock_logger.error.assert_called_once()
140
+ mock_exit.assert_called_once_with(1)
141
+
142
+
143
+ class TestRunCommand:
144
+ """Tests for the run command."""
145
+
146
+ def test_run_command_success(self, temp_python_file):
147
+ """Test successful run command execution."""
148
+ with (
149
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
150
+ patch("fastmcp.cli.run.import_server") as mock_import,
151
+ patch("fastmcp.cli.run.logger") as mock_logger,
152
+ ):
153
+ mock_parse.return_value = (temp_python_file, None)
154
+ mock_server = MagicMock()
155
+ mock_server.name = "test_server"
156
+ mock_import.return_value = mock_server
157
+
158
+ result = runner.invoke(cli.app, ["run", str(temp_python_file)])
159
+ assert result.exit_code == 0
160
+ mock_server.run.assert_called_once_with()
161
+ mock_logger.debug.assert_called_with(
162
+ f'Found server "test_server" in {temp_python_file}'
163
+ )
164
+
165
+ def test_run_command_with_transport(self, temp_python_file):
166
+ """Test run command with transport option."""
167
+ with (
168
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
169
+ patch("fastmcp.cli.run.import_server") as mock_import,
170
+ ):
171
+ mock_parse.return_value = (temp_python_file, None)
172
+ mock_server = MagicMock()
173
+ mock_server.name = "test_server"
174
+ mock_import.return_value = mock_server
175
+
176
+ result = runner.invoke(
177
+ cli.app, ["run", str(temp_python_file), "--transport", "sse"]
178
+ )
179
+ assert result.exit_code == 0
180
+ mock_server.run.assert_called_once_with(transport="sse")
181
+
182
+ def test_run_command_with_host(self, temp_python_file):
183
+ """Test run command with host option."""
184
+ with (
185
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
186
+ patch("fastmcp.cli.run.import_server") as mock_import,
187
+ ):
188
+ mock_parse.return_value = (temp_python_file, None)
189
+ mock_server = MagicMock()
190
+ mock_server.name = "test_server"
191
+ mock_import.return_value = mock_server
192
+
193
+ result = runner.invoke(
194
+ cli.app, ["run", str(temp_python_file), "--host", "0.0.0.0"]
195
+ )
196
+ assert result.exit_code == 0
197
+ mock_server.run.assert_called_once_with(host="0.0.0.0")
198
+
199
+ def test_run_command_with_port(self, temp_python_file):
200
+ """Test run command with port option."""
201
+ with (
202
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
203
+ patch("fastmcp.cli.run.import_server") as mock_import,
204
+ ):
205
+ mock_parse.return_value = (temp_python_file, None)
206
+ mock_server = MagicMock()
207
+ mock_server.name = "test_server"
208
+ mock_import.return_value = mock_server
209
+
210
+ result = runner.invoke(
211
+ cli.app, ["run", str(temp_python_file), "--port", "8080"]
212
+ )
213
+ assert result.exit_code == 0
214
+ mock_server.run.assert_called_once_with(port=8080)
215
+
216
+ def test_run_command_with_log_level(self, temp_python_file):
217
+ """Test run command with log level option."""
218
+ with (
219
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
220
+ patch("fastmcp.cli.run.import_server") as mock_import,
221
+ ):
222
+ mock_parse.return_value = (temp_python_file, None)
223
+ mock_server = MagicMock()
224
+ mock_server.name = "test_server"
225
+ mock_import.return_value = mock_server
226
+
227
+ result = runner.invoke(
228
+ cli.app, ["run", str(temp_python_file), "--log-level", "DEBUG"]
229
+ )
230
+ assert result.exit_code == 0
231
+ mock_server.run.assert_called_once_with(log_level="DEBUG")
232
+
233
+ def test_run_command_with_multiple_options(self, temp_python_file):
234
+ """Test run command with multiple options."""
235
+ with (
236
+ patch("fastmcp.cli.run.parse_file_path") as mock_parse,
237
+ patch("fastmcp.cli.run.import_server") as mock_import,
238
+ ):
239
+ mock_parse.return_value = (temp_python_file, None)
240
+ mock_server = MagicMock()
241
+ mock_server.name = "test_server"
242
+ mock_import.return_value = mock_server
243
+
244
+ result = runner.invoke(
245
+ cli.app,
246
+ [
247
+ "run",
248
+ str(temp_python_file),
249
+ "--transport",
250
+ "sse",
251
+ "--host",
252
+ "0.0.0.0",
253
+ "--port",
254
+ "8080",
255
+ "--log-level",
256
+ "DEBUG",
257
+ ],
258
+ )
259
+ assert result.exit_code == 0
260
+ mock_server.run.assert_called_once_with(
261
+ transport="sse", host="0.0.0.0", port=8080, log_level="DEBUG"
262
+ )