Jeremiah Lowin commited on
Commit
2ecf7ae
·
unverified ·
1 Parent(s): 6090024

Add Claude Code install integration (#1053)

Browse files

* Add Cursor support

* Use url-safe encoding

* Add claude code integration

* Delete test_install_dependencies.py

* Fix windows tests

docs/integrations/claude-code.mdx CHANGED
@@ -1,24 +1,26 @@
1
  ---
2
  title: Claude Code + FastMCP
3
  sidebarTitle: Claude Code
4
- description: Connect FastMCP servers to Claude Code
5
  icon: message-smile
6
  tag: NEW
7
  ---
8
 
9
- Claude Code supports MCP servers through multiple transport methods, allowing you to extend Claude's capabilities with custom tools, resources, and prompts from your FastMCP servers.
 
 
10
 
11
  <Note>
12
- Claude Code supports both local and remote MCP servers with flexible configuration options. See the [Claude Code MCP documentation](https://docs.anthropic.com/en/docs/claude-code/mcp) for other transport methods.
13
  </Note>
14
 
15
- <Tip>
16
- Claude Code provides built-in MCP management commands to easily add, configure, and authenticate your FastMCP servers.
17
- </Tip>
18
 
19
  ## Create a Server
20
 
21
- You can create FastMCP servers using STDIO transport, remote HTTP servers, or local HTTP servers. This example shows one common approach: running an HTTP server locally for development.
22
 
23
  ```python server.py
24
  import random
@@ -32,29 +34,101 @@ def roll_dice(n_dice: int) -> list[int]:
32
  return [random.randint(1, 6) for _ in range(n_dice)]
33
 
34
  if __name__ == "__main__":
35
- mcp.run(transport="http", port=8000)
36
  ```
37
 
38
- ## Connect to Claude Code
 
 
 
39
 
40
- Start your server and add it to Claude Code:
41
 
42
  ```bash
43
- # Start your server first
44
- python server.py
45
  ```
46
 
47
- Then add it to Claude Code:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  ```bash
49
- claude mcp add dice --transport http http://localhost:8000/mcp/
50
  ```
51
 
52
- ## Using Your Server
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
- Once connected, Claude Code will automatically discover and use your server's tools when relevant:
 
 
 
 
 
 
55
 
 
 
56
  ```
57
- Roll some dice for me
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  ```
59
 
60
- Claude will call your `roll_dice` tool and provide the results. If your server provides resources, you can reference them with `@` mentions like `@dice:file://path/to/resource`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Claude Code + FastMCP
3
  sidebarTitle: Claude Code
4
+ description: Install and use FastMCP servers in Claude Code
5
  icon: message-smile
6
  tag: NEW
7
  ---
8
 
9
+ import { VersionBadge } from "/snippets/version-badge.mdx"
10
+
11
+ Claude Code supports MCP servers through multiple transport methods including STDIO, SSE, and HTTP, allowing you to extend Claude's capabilities with custom tools, resources, and prompts from your FastMCP servers.
12
 
13
  <Note>
14
+ This guide focuses specifically on installing local FastMCP server files directly into Claude Code using STDIO transport. For deploying remote servers using SSE or HTTP transports, see the [Claude Code MCP documentation](https://docs.anthropic.com/en/docs/claude-code/mcp).
15
  </Note>
16
 
17
+ ## Requirements
18
+
19
+ This integration uses STDIO transport to run your FastMCP server locally. For remote deployments, you can run your FastMCP server with HTTP or SSE transport and configure it directly using Claude Code's built-in MCP management commands.
20
 
21
  ## Create a Server
22
 
23
+ The examples in this guide will use the following simple dice-rolling server, saved as `server.py`.
24
 
25
  ```python server.py
26
  import random
 
34
  return [random.randint(1, 6) for _ in range(n_dice)]
35
 
36
  if __name__ == "__main__":
37
+ mcp.run()
38
  ```
39
 
40
+ ## Install the Server
41
+
42
+ ### FastMCP CLI
43
+ <VersionBadge version="2.10.3" />
44
 
45
+ The easiest way to install a FastMCP server in Claude Code is using the `fastmcp install claude-code` command. This automatically handles the configuration, dependency management, and calls Claude Code's built-in MCP management system.
46
 
47
  ```bash
48
+ fastmcp install claude-code server.py
 
49
  ```
50
 
51
+ The install command supports the same `file.py:object` notation as the `run` command. If no object is specified, it will automatically look for a FastMCP server object named `mcp`, `server`, or `app` in your file:
52
+
53
+ ```bash
54
+ # These are equivalent if your server object is named 'mcp'
55
+ fastmcp install claude-code server.py
56
+ fastmcp install claude-code server.py:mcp
57
+
58
+ # Use explicit object name if your server has a different name
59
+ fastmcp install claude-code server.py:my_custom_server
60
+ ```
61
+
62
+ The command will automatically configure the server with Claude Code's `claude mcp add` command.
63
+
64
+ #### Dependencies
65
+
66
+ If your server has dependencies, include them with the `--with` flag:
67
+
68
  ```bash
69
+ fastmcp install claude-code server.py --with pandas --with requests
70
  ```
71
 
72
+ Alternatively, you can specify dependencies directly in your server code:
73
+
74
+ ```python server.py
75
+ from fastmcp import FastMCP
76
+
77
+ mcp = FastMCP(
78
+ name="Dice Roller",
79
+ dependencies=["pandas", "requests"]
80
+ )
81
+ ```
82
+
83
+ #### Environment Variables
84
+
85
+ If your server needs environment variables (like API keys), you must include them:
86
 
87
+ ```bash
88
+ fastmcp install claude-code server.py --name "Weather Server" \
89
+ --env-var API_KEY=your-api-key \
90
+ --env-var DEBUG=true
91
+ ```
92
+
93
+ Or load them from a `.env` file:
94
 
95
+ ```bash
96
+ fastmcp install claude-code server.py --name "Weather Server" --env-file .env
97
  ```
98
+
99
+ <Warning>
100
+ **Claude Code must be installed**. The integration looks for the Claude Code CLI at the default installation location (`~/.claude/local/claude`) and uses the `claude mcp add` command to register servers.
101
+ </Warning>
102
+
103
+ ### Manual Configuration
104
+
105
+ For more control over the configuration, you can manually use Claude Code's built-in MCP management commands:
106
+
107
+ ```bash
108
+ # Add a server with custom configuration
109
+ claude mcp add dice-roller -- uv run --with fastmcp fastmcp run server.py
110
+
111
+ # Add with environment variables
112
+ claude mcp add weather-server -e API_KEY=secret -e DEBUG=true -- uv run --with fastmcp fastmcp run server.py
113
+
114
+ # Add with specific scope (local, user, or project)
115
+ claude mcp add my-server --scope user -- uv run --with fastmcp fastmcp run server.py
116
  ```
117
 
118
+ ## Using the Server
119
+
120
+ Once your server is installed, you can start using your FastMCP server with Claude Code.
121
+
122
+ Try asking Claude something like:
123
+
124
+ > "Roll some dice for me"
125
+
126
+ Claude will automatically detect your `roll_dice` tool and use it to fulfill your request, returning something like:
127
+
128
+ > I'll roll some dice for you! Here are your results: [4, 2, 6]
129
+ >
130
+ > You rolled three dice and got a 4, a 2, and a 6!
131
+
132
+ Claude Code can now access all the tools, resources, and prompts you've defined in your FastMCP server.
133
+
134
+ If your server provides resources, you can reference them with `@` mentions using the format `@server:protocol://resource/path`. If your server provides prompts, you can use them as slash commands with `/mcp__servername__promptname`.
docs/patterns/cli.mdx CHANGED
@@ -148,10 +148,12 @@ fastmcp dev server.py -e . --with pandas --with matplotlib
148
 
149
  Install a MCP server in MCP client applications. FastMCP currently supports the following clients:
150
 
 
151
  - **Claude Desktop** - Installs via direct configuration file modification
152
  - **Cursor** - Installs via deeplink that opens Cursor for user confirmation
153
 
154
  ```bash
 
155
  fastmcp install claude-desktop server.py
156
  fastmcp install cursor server.py
157
  ```
@@ -195,6 +197,9 @@ fastmcp install claude-desktop server.py:my_server
195
  # With custom name and dependencies
196
  fastmcp install claude-desktop server.py:my_server -n "My Analysis Server" --with pandas
197
 
 
 
 
198
  # Install in Cursor with environment variables
199
  fastmcp install cursor server.py --env-var API_KEY=secret --env-var DEBUG=true
200
 
 
148
 
149
  Install a MCP server in MCP client applications. FastMCP currently supports the following clients:
150
 
151
+ - **Claude Code** - Installs via Claude Code's built-in MCP management system
152
  - **Claude Desktop** - Installs via direct configuration file modification
153
  - **Cursor** - Installs via deeplink that opens Cursor for user confirmation
154
 
155
  ```bash
156
+ fastmcp install claude-code server.py
157
  fastmcp install claude-desktop server.py
158
  fastmcp install cursor server.py
159
  ```
 
197
  # With custom name and dependencies
198
  fastmcp install claude-desktop server.py:my_server -n "My Analysis Server" --with pandas
199
 
200
+ # Install in Claude Code with environment variables
201
+ fastmcp install claude-code server.py --env-var API_KEY=secret --env-var DEBUG=true
202
+
203
  # Install in Cursor with environment variables
204
  fastmcp install cursor server.py --env-var API_KEY=secret --env-var DEBUG=true
205
 
src/fastmcp/cli/install/claude_code.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Claude Code integration for FastMCP install."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+ from rich import print
9
+
10
+ from fastmcp.utilities.logging import get_logger
11
+
12
+ logger = get_logger(__name__)
13
+
14
+
15
+ def find_claude_command() -> str | None:
16
+ """Find the Claude Code CLI command."""
17
+ # Check the default installation location
18
+ default_path = Path.home() / ".claude" / "local" / "claude"
19
+ if default_path.exists():
20
+ try:
21
+ result = subprocess.run(
22
+ [str(default_path), "--version"],
23
+ check=True,
24
+ capture_output=True,
25
+ text=True,
26
+ )
27
+ if "Claude Code" in result.stdout:
28
+ return str(default_path)
29
+ except (subprocess.CalledProcessError, FileNotFoundError):
30
+ pass
31
+
32
+ return None
33
+
34
+
35
+ def check_claude_code_available() -> bool:
36
+ """Check if Claude Code CLI is available."""
37
+ return find_claude_command() is not None
38
+
39
+
40
+ def install_claude_code(
41
+ file: Path,
42
+ server_object: str | None,
43
+ name: str,
44
+ *,
45
+ with_editable: Path | None = None,
46
+ with_packages: list[str] | None = None,
47
+ env_vars: dict[str, str] | None = None,
48
+ ) -> bool:
49
+ """Install FastMCP server in Claude Code.
50
+
51
+ Args:
52
+ file: Path to the server file
53
+ server_object: Optional server object name (for :object suffix)
54
+ name: Name for the server in Claude Code
55
+ with_editable: Optional directory to install in editable mode
56
+ with_packages: Optional list of additional packages to install
57
+ env_vars: Optional dictionary of environment variables
58
+
59
+ Returns:
60
+ True if installation was successful, False otherwise
61
+ """
62
+ # Check if Claude Code CLI is available
63
+ claude_cmd = find_claude_command()
64
+ if not claude_cmd:
65
+ print(
66
+ "[red]Claude Code CLI not found.[/red]\n"
67
+ "[blue]Please ensure Claude Code is installed. Try running 'claude --version' to verify.[/blue]"
68
+ )
69
+ return False
70
+
71
+ # Build uv run command
72
+ args = ["run"]
73
+
74
+ # Collect all packages in a set to deduplicate
75
+ packages = {"fastmcp"}
76
+ if with_packages:
77
+ packages.update(pkg for pkg in with_packages if pkg)
78
+
79
+ # Add all packages with --with
80
+ for pkg in sorted(packages):
81
+ args.extend(["--with", pkg])
82
+
83
+ if with_editable:
84
+ args.extend(["--with-editable", str(with_editable)])
85
+
86
+ # Build server spec from parsed components
87
+ if server_object:
88
+ server_spec = f"{file.resolve()}:{server_object}"
89
+ else:
90
+ server_spec = str(file.resolve())
91
+
92
+ # Add fastmcp run command
93
+ args.extend(["fastmcp", "run", server_spec])
94
+
95
+ # Build claude mcp add command
96
+ cmd_parts = [claude_cmd, "mcp", "add"]
97
+
98
+ # Add environment variables if specified (before the name and command)
99
+ if env_vars:
100
+ for key, value in env_vars.items():
101
+ cmd_parts.extend(["-e", f"{key}={value}"])
102
+
103
+ # Add server name and command
104
+ cmd_parts.extend([name, "--"])
105
+ cmd_parts.extend(["uv"] + args)
106
+
107
+ try:
108
+ # Run the claude mcp add command
109
+ subprocess.run(cmd_parts, check=True, capture_output=True, text=True)
110
+ return True
111
+ except subprocess.CalledProcessError as e:
112
+ print(
113
+ f"[red]Failed to install '[bold]{name}[/bold]' in Claude Code: {e.stderr.strip() if e.stderr else str(e)}[/red]"
114
+ )
115
+ return False
116
+ except Exception as e:
117
+ print(f"[red]Failed to install '[bold]{name}[/bold]' in Claude Code: {e}[/red]")
118
+ return False
src/fastmcp/cli/install/claude_desktop.py CHANGED
@@ -33,7 +33,8 @@ def get_claude_config_path() -> Path | None:
33
 
34
 
35
  def install_claude_desktop(
36
- server_spec: str,
 
37
  name: str,
38
  *,
39
  with_editable: Path | None = None,
@@ -43,7 +44,8 @@ def install_claude_desktop(
43
  """Install FastMCP server in Claude Desktop.
44
 
45
  Args:
46
- server_spec: Path to the server file, optionally with :object suffix
 
47
  name: Name for the server in Claude's config
48
  with_editable: Optional directory to install in editable mode
49
  with_packages: Optional list of additional packages to install
@@ -77,13 +79,11 @@ def install_claude_desktop(
77
  if with_editable:
78
  args.extend(["--with-editable", str(with_editable)])
79
 
80
- # Convert file path to absolute before adding to command
81
- # Split off any :object suffix first
82
- if ":" in server_spec:
83
- file_path, server_object = server_spec.rsplit(":", 1)
84
- server_spec = f"{Path(file_path).resolve()}:{server_object}"
85
  else:
86
- server_spec = str(Path(server_spec).resolve())
87
 
88
  # Add fastmcp run command
89
  args.extend(["fastmcp", "run", server_spec])
 
33
 
34
 
35
  def install_claude_desktop(
36
+ file: Path,
37
+ server_object: str | None,
38
  name: str,
39
  *,
40
  with_editable: Path | None = None,
 
44
  """Install FastMCP server in Claude Desktop.
45
 
46
  Args:
47
+ file: Path to the server file
48
+ server_object: Optional server object name (for :object suffix)
49
  name: Name for the server in Claude's config
50
  with_editable: Optional directory to install in editable mode
51
  with_packages: Optional list of additional packages to install
 
79
  if with_editable:
80
  args.extend(["--with-editable", str(with_editable)])
81
 
82
+ # Build server spec from parsed components
83
+ if server_object:
84
+ server_spec = f"{file.resolve()}:{server_object}"
 
 
85
  else:
86
+ server_spec = str(file.resolve())
87
 
88
  # Add fastmcp run command
89
  args.extend(["fastmcp", "run", server_spec])
src/fastmcp/cli/install/cursor.py CHANGED
@@ -64,7 +64,8 @@ def open_deeplink(deeplink: str) -> bool:
64
 
65
 
66
  def install_cursor(
67
- server_spec: str,
 
68
  name: str,
69
  *,
70
  with_editable: Path | None = None,
@@ -74,7 +75,8 @@ def install_cursor(
74
  """Install FastMCP server in Cursor.
75
 
76
  Args:
77
- server_spec: Path to the server file, optionally with :object suffix
 
78
  name: Name for the server in Cursor's config
79
  with_editable: Optional directory to install in editable mode
80
  with_packages: Optional list of additional packages to install
@@ -98,13 +100,11 @@ def install_cursor(
98
  if with_editable:
99
  args.extend(["--with-editable", str(with_editable)])
100
 
101
- # Convert file path to absolute before adding to command
102
- # Split off any :object suffix first
103
- if ":" in server_spec:
104
- file_path, server_object = server_spec.rsplit(":", 1)
105
- server_spec = f"{Path(file_path).resolve()}:{server_object}"
106
  else:
107
- server_spec = str(Path(server_spec).resolve())
108
 
109
  # Add fastmcp run command
110
  args.extend(["fastmcp", "run", server_spec])
 
64
 
65
 
66
  def install_cursor(
67
+ file: Path,
68
+ server_object: str | None,
69
  name: str,
70
  *,
71
  with_editable: Path | None = None,
 
75
  """Install FastMCP server in Cursor.
76
 
77
  Args:
78
+ file: Path to the server file
79
+ server_object: Optional server object name (for :object suffix)
80
  name: Name for the server in Cursor's config
81
  with_editable: Optional directory to install in editable mode
82
  with_packages: Optional list of additional packages to install
 
100
  if with_editable:
101
  args.extend(["--with-editable", str(with_editable)])
102
 
103
+ # Build server spec from parsed components
104
+ if server_object:
105
+ server_spec = f"{file.resolve()}:{server_object}"
 
 
106
  else:
107
+ server_spec = str(file.resolve())
108
 
109
  # Add fastmcp run command
110
  args.extend(["fastmcp", "run", server_spec])
src/fastmcp/cli/install/install.py CHANGED
@@ -14,6 +14,7 @@ from rich import print
14
  from fastmcp.cli.run import import_server, parse_file_path
15
  from fastmcp.utilities.logging import get_logger
16
 
 
17
  from .claude_desktop import install_claude_desktop
18
  from .cursor import install_cursor
19
 
@@ -23,6 +24,7 @@ logger = get_logger(__name__)
23
  class Client(str, Enum):
24
  """Supported MCP clients."""
25
 
 
26
  CLAUDE_DESKTOP = "claude-desktop"
27
  CURSOR = "cursor"
28
 
@@ -142,9 +144,19 @@ def install(
142
  env_dict[key] = value
143
 
144
  # Route to appropriate installer
145
- if client == Client.CLAUDE_DESKTOP:
 
 
 
 
 
 
 
 
 
146
  success = install_claude_desktop(
147
- server_spec=server_spec,
 
148
  name=name,
149
  with_editable=with_editable,
150
  with_packages=with_packages,
@@ -152,7 +164,8 @@ def install(
152
  )
153
  elif client == Client.CURSOR:
154
  success = install_cursor(
155
- server_spec=server_spec,
 
156
  name=name,
157
  with_editable=with_editable,
158
  with_packages=with_packages,
@@ -160,7 +173,7 @@ def install(
160
  )
161
  else:
162
  print(
163
- f"[red bold]Unknown client: {client!r}[/red bold]. Supported clients: [bold]{Client.CLAUDE_DESKTOP}[/bold], [bold]{Client.CURSOR}[/bold]"
164
  )
165
  raise typer.Exit(1)
166
 
 
14
  from fastmcp.cli.run import import_server, parse_file_path
15
  from fastmcp.utilities.logging import get_logger
16
 
17
+ from .claude_code import install_claude_code
18
  from .claude_desktop import install_claude_desktop
19
  from .cursor import install_cursor
20
 
 
24
  class Client(str, Enum):
25
  """Supported MCP clients."""
26
 
27
+ CLAUDE_CODE = "claude-code"
28
  CLAUDE_DESKTOP = "claude-desktop"
29
  CURSOR = "cursor"
30
 
 
144
  env_dict[key] = value
145
 
146
  # Route to appropriate installer
147
+ if client == Client.CLAUDE_CODE:
148
+ success = install_claude_code(
149
+ file=file,
150
+ server_object=server_object,
151
+ name=name,
152
+ with_editable=with_editable,
153
+ with_packages=with_packages,
154
+ env_vars=env_dict,
155
+ )
156
+ elif client == Client.CLAUDE_DESKTOP:
157
  success = install_claude_desktop(
158
+ file=file,
159
+ server_object=server_object,
160
  name=name,
161
  with_editable=with_editable,
162
  with_packages=with_packages,
 
164
  )
165
  elif client == Client.CURSOR:
166
  success = install_cursor(
167
+ file=file,
168
+ server_object=server_object,
169
  name=name,
170
  with_editable=with_editable,
171
  with_packages=with_packages,
 
173
  )
174
  else:
175
  print(
176
+ f"[red bold]Unknown client: {client!r}[/red bold]. Supported clients: [bold]{Client.CLAUDE_CODE}[/bold], [bold]{Client.CLAUDE_DESKTOP}[/bold], [bold]{Client.CURSOR}[/bold]"
177
  )
178
  raise typer.Exit(1)
179
 
tests/cli/test_claude_code.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for Claude Code CLI integration."""
2
+
3
+ from pathlib import Path
4
+ from unittest.mock import MagicMock, patch
5
+
6
+ from fastmcp.cli.install.claude_code import (
7
+ check_claude_code_available,
8
+ find_claude_command,
9
+ install_claude_code,
10
+ )
11
+
12
+
13
+ class TestFindClaudeCommand:
14
+ """Test find_claude_command function."""
15
+
16
+ @patch("subprocess.run")
17
+ @patch("pathlib.Path.exists")
18
+ def test_finds_command_in_default_location(self, mock_exists, mock_run):
19
+ """Should find claude in default installation location."""
20
+ mock_exists.return_value = True
21
+ mock_run.return_value = MagicMock(stdout="1.0.43 (Claude Code)")
22
+
23
+ result = find_claude_command()
24
+
25
+ expected_path = str(Path.home() / ".claude" / "local" / "claude")
26
+ assert result == expected_path
27
+ mock_run.assert_called_once_with(
28
+ [expected_path, "--version"], check=True, capture_output=True, text=True
29
+ )
30
+
31
+ @patch("subprocess.run")
32
+ @patch("pathlib.Path.exists")
33
+ def test_rejects_non_claude_code_binary(self, mock_exists, mock_run):
34
+ """Should reject binary that isn't Claude Code."""
35
+ mock_exists.return_value = True
36
+ mock_run.return_value = MagicMock(stdout="Some other claude 1.0.0")
37
+
38
+ result = find_claude_command()
39
+
40
+ assert result is None
41
+
42
+ @patch("subprocess.run")
43
+ @patch("pathlib.Path.exists")
44
+ def test_handles_subprocess_error(self, mock_exists, mock_run):
45
+ """Should handle subprocess errors gracefully."""
46
+ from subprocess import CalledProcessError
47
+
48
+ mock_exists.return_value = True
49
+ mock_run.side_effect = CalledProcessError(1, "claude")
50
+
51
+ result = find_claude_command()
52
+
53
+ assert result is None
54
+
55
+ @patch("pathlib.Path.exists")
56
+ def test_no_command_found(self, mock_exists):
57
+ """Should return None when binary doesn't exist."""
58
+ mock_exists.return_value = False
59
+
60
+ result = find_claude_command()
61
+
62
+ assert result is None
63
+
64
+
65
+ class TestCheckClaudeCodeAvailable:
66
+ """Test check_claude_code_available function."""
67
+
68
+ @patch("fastmcp.cli.install.claude_code.find_claude_command")
69
+ def test_available_when_command_found(self, mock_find):
70
+ """Should return True when claude command is found."""
71
+ mock_find.return_value = "/usr/local/bin/claude"
72
+
73
+ result = check_claude_code_available()
74
+
75
+ assert result is True
76
+
77
+ @patch("fastmcp.cli.install.claude_code.find_claude_command")
78
+ def test_not_available_when_command_not_found(self, mock_find):
79
+ """Should return False when claude command is not found."""
80
+ mock_find.return_value = None
81
+
82
+ result = check_claude_code_available()
83
+
84
+ assert result is False
85
+
86
+
87
+ class TestInstallClaudeCode:
88
+ """Test install_claude_code function."""
89
+
90
+ @patch("fastmcp.cli.install.claude_code.find_claude_command")
91
+ @patch("fastmcp.cli.install.claude_code.print")
92
+ def test_fails_when_claude_not_found(self, mock_print, mock_find):
93
+ """Should return False and print error when Claude Code CLI not found."""
94
+ mock_find.return_value = None
95
+
96
+ result = install_claude_code(Path("server.py"), None, "test-server")
97
+
98
+ assert result is False
99
+ mock_print.assert_called_once()
100
+ assert "Claude Code CLI not found" in str(mock_print.call_args)
101
+
102
+ @patch("fastmcp.cli.install.claude_code.find_claude_command")
103
+ @patch("subprocess.run")
104
+ def test_successful_installation(self, mock_run, mock_find):
105
+ """Should successfully install when command succeeds."""
106
+ mock_find.return_value = "/usr/local/bin/claude"
107
+ mock_run.return_value = MagicMock()
108
+
109
+ result = install_claude_code(Path("server.py"), None, "test-server")
110
+
111
+ assert result is True
112
+ mock_run.assert_called_once()
113
+
114
+ # Check the command that was run
115
+ call_args = mock_run.call_args[0][0]
116
+ assert call_args[0] == "/usr/local/bin/claude"
117
+ assert "mcp" in call_args
118
+ assert "add" in call_args
119
+ assert "test-server" in call_args
120
+ assert "--" in call_args
121
+ assert "uv" in call_args
122
+
123
+ @patch("fastmcp.cli.install.claude_code.find_claude_command")
124
+ @patch("subprocess.run")
125
+ @patch("fastmcp.cli.install.claude_code.print")
126
+ def test_handles_subprocess_error(self, mock_print, mock_run, mock_find):
127
+ """Should handle subprocess errors and return False."""
128
+ from subprocess import CalledProcessError
129
+
130
+ mock_find.return_value = "/usr/local/bin/claude"
131
+ mock_run.side_effect = CalledProcessError(
132
+ 1, "claude", stderr="Permission denied"
133
+ )
134
+
135
+ result = install_claude_code(Path("server.py"), None, "test-server")
136
+
137
+ assert result is False
138
+ mock_print.assert_called_once()
139
+ assert "Failed to install" in str(mock_print.call_args)
140
+ assert "Permission denied" in str(mock_print.call_args)
141
+
142
+ @patch("fastmcp.cli.install.claude_code.find_claude_command")
143
+ @patch("subprocess.run")
144
+ def test_builds_correct_command_with_options(self, mock_run, mock_find):
145
+ """Should build correct command with all options."""
146
+ mock_find.return_value = "/usr/local/bin/claude"
147
+ mock_run.return_value = MagicMock()
148
+
149
+ install_claude_code(
150
+ file=Path("server.py"),
151
+ server_object="custom_server",
152
+ name="test-server",
153
+ with_editable=Path("/path/to/editable"),
154
+ with_packages=["pandas", "requests"],
155
+ env_vars={"API_KEY": "secret", "DEBUG": "true"},
156
+ )
157
+
158
+ # Check the command that was run
159
+ call_args = mock_run.call_args[0][0]
160
+
161
+ # Should have claude command
162
+ assert call_args[0] == "/usr/local/bin/claude"
163
+ assert "mcp" in call_args
164
+ assert "add" in call_args
165
+
166
+ # Should have environment variables
167
+ assert "-e" in call_args
168
+ env_vars = []
169
+ for i, arg in enumerate(call_args):
170
+ if arg == "-e" and i + 1 < len(call_args):
171
+ env_vars.append(call_args[i + 1])
172
+ assert "API_KEY=secret" in env_vars
173
+ assert "DEBUG=true" in env_vars
174
+
175
+ # Should have server name
176
+ assert "test-server" in call_args
177
+
178
+ # Should have separator
179
+ assert "--" in call_args
180
+
181
+ # Should have uv command with packages
182
+ assert "uv" in call_args
183
+ assert "run" in call_args
184
+ assert "--with" in call_args
185
+ assert "fastmcp" in call_args
186
+ assert "pandas" in call_args
187
+ assert "requests" in call_args
188
+ assert "--with-editable" in call_args
189
+ assert str(Path("/path/to/editable")) in call_args
190
+
191
+ @patch("fastmcp.cli.install.claude_code.find_claude_command")
192
+ @patch("subprocess.run")
193
+ def test_resolves_absolute_paths(self, mock_run, mock_find):
194
+ """Should resolve server spec to absolute path."""
195
+ mock_find.return_value = "/usr/local/bin/claude"
196
+ mock_run.return_value = MagicMock()
197
+
198
+ install_claude_code(Path("server.py"), None, "test-server")
199
+
200
+ call_args = mock_run.call_args[0][0]
201
+
202
+ # Find the server spec after "fastmcp run"
203
+ server_spec_in_args = None
204
+ for i, arg in enumerate(call_args):
205
+ if (
206
+ arg == "fastmcp"
207
+ and i + 2 < len(call_args)
208
+ and call_args[i + 1] == "run"
209
+ ):
210
+ server_spec_in_args = call_args[i + 2]
211
+ break
212
+
213
+ assert server_spec_in_args is not None
214
+ assert str(Path("server.py").resolve()) in server_spec_in_args
215
+
216
+ @patch("fastmcp.cli.install.claude_code.find_claude_command")
217
+ @patch("subprocess.run")
218
+ def test_handles_server_spec_with_object(self, mock_run, mock_find):
219
+ """Should correctly handle server spec with object notation."""
220
+ mock_find.return_value = "/usr/local/bin/claude"
221
+ mock_run.return_value = MagicMock()
222
+
223
+ install_claude_code(Path("server.py"), "custom_object", "test-server")
224
+
225
+ call_args = mock_run.call_args[0][0]
226
+
227
+ # Find the server spec after "fastmcp run"
228
+ server_spec_in_args = None
229
+ for i, arg in enumerate(call_args):
230
+ if (
231
+ arg == "fastmcp"
232
+ and i + 2 < len(call_args)
233
+ and call_args[i + 1] == "run"
234
+ ):
235
+ server_spec_in_args = call_args[i + 2]
236
+ break
237
+
238
+ assert server_spec_in_args is not None
239
+ assert ":custom_object" in server_spec_in_args
240
+ assert str(Path("server.py").resolve()) in server_spec_in_args
241
+
242
+ @patch("fastmcp.cli.install.claude_code.find_claude_command")
243
+ @patch("subprocess.run")
244
+ def test_deduplicates_packages(self, mock_run, mock_find):
245
+ """Should deduplicate packages in the command."""
246
+ mock_find.return_value = "/usr/local/bin/claude"
247
+ mock_run.return_value = MagicMock()
248
+
249
+ install_claude_code(
250
+ file=Path("server.py"),
251
+ server_object=None,
252
+ name="test-server",
253
+ with_packages=["pandas", "fastmcp", "pandas"], # duplicates
254
+ )
255
+
256
+ call_args = mock_run.call_args[0][0]
257
+
258
+ # Count occurrences of pandas
259
+ pandas_count = sum(1 for arg in call_args if arg == "pandas")
260
+ fastmcp_count = sum(1 for arg in call_args if arg == "fastmcp")
261
+
262
+ # Should only appear once each for the package (fastmcp appears twice: once as package, once as command)
263
+ assert pandas_count == 1
264
+ assert fastmcp_count == 2 # Once in --with fastmcp, once in fastmcp run
tests/cli/test_cursor.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for Cursor CLI integration."""
2
+
3
+ import base64
4
+ import json
5
+ from pathlib import Path
6
+ from unittest.mock import patch
7
+
8
+ from fastmcp.cli.install.cursor import (
9
+ generate_cursor_deeplink,
10
+ install_cursor,
11
+ open_deeplink,
12
+ )
13
+ from fastmcp.mcp_config import StdioMCPServer
14
+
15
+
16
+ class TestGenerateCursorDeeplink:
17
+ """Test generate_cursor_deeplink function."""
18
+
19
+ def test_generates_valid_deeplink(self):
20
+ """Should generate a valid Cursor deeplink with base64 encoded config."""
21
+ server_config = StdioMCPServer(
22
+ command="uv",
23
+ args=["run", "--with", "fastmcp", "fastmcp", "run", "server.py"],
24
+ env={"API_KEY": "secret"},
25
+ )
26
+
27
+ deeplink = generate_cursor_deeplink("test-server", server_config)
28
+
29
+ assert deeplink.startswith("cursor://anysphere.cursor-deeplink/mcp/install?")
30
+ assert "name=test-server" in deeplink
31
+ assert "config=" in deeplink
32
+
33
+ def test_config_is_url_safe_base64(self):
34
+ """Should use URL-safe base64 encoding for the config."""
35
+ server_config = StdioMCPServer(
36
+ command="test",
37
+ args=["arg1", "arg2"],
38
+ )
39
+
40
+ deeplink = generate_cursor_deeplink("test", server_config)
41
+
42
+ # Extract the config parameter
43
+ config_param = deeplink.split("config=")[1]
44
+
45
+ # Should be decodable as URL-safe base64
46
+ decoded = base64.urlsafe_b64decode(config_param.encode())
47
+ config_data = json.loads(decoded)
48
+
49
+ assert config_data["command"] == "test"
50
+ assert config_data["args"] == ["arg1", "arg2"]
51
+
52
+ def test_excludes_none_values(self):
53
+ """Should exclude None values from the configuration."""
54
+ server_config = StdioMCPServer(
55
+ command="test",
56
+ args=["arg1"],
57
+ timeout=None, # This should be excluded
58
+ )
59
+
60
+ deeplink = generate_cursor_deeplink("test", server_config)
61
+ config_param = deeplink.split("config=")[1]
62
+ decoded = base64.urlsafe_b64decode(config_param.encode())
63
+ config_data = json.loads(decoded)
64
+
65
+ assert "timeout" not in config_data
66
+
67
+
68
+ class TestOpenDeeplink:
69
+ """Test open_deeplink function."""
70
+
71
+ @patch("subprocess.run")
72
+ @patch("fastmcp.cli.install.cursor.sys.platform", "darwin")
73
+ def test_opens_on_macos(self, mock_run):
74
+ """Should use 'open' command on macOS."""
75
+ mock_run.return_value = None
76
+
77
+ result = open_deeplink("cursor://test")
78
+
79
+ assert result is True
80
+ mock_run.assert_called_once_with(
81
+ ["open", "cursor://test"], check=True, capture_output=True
82
+ )
83
+
84
+ @patch("subprocess.run")
85
+ @patch("fastmcp.cli.install.cursor.sys.platform", "win32")
86
+ def test_opens_on_windows(self, mock_run):
87
+ """Should use 'start' command on Windows."""
88
+ mock_run.return_value = None
89
+
90
+ result = open_deeplink("cursor://test")
91
+
92
+ assert result is True
93
+ mock_run.assert_called_once_with(
94
+ ["start", "cursor://test"], shell=True, check=True, capture_output=True
95
+ )
96
+
97
+ @patch("subprocess.run")
98
+ @patch("fastmcp.cli.install.cursor.sys.platform", "linux")
99
+ def test_opens_on_linux(self, mock_run):
100
+ """Should use 'xdg-open' command on Linux."""
101
+ mock_run.return_value = None
102
+
103
+ result = open_deeplink("cursor://test")
104
+
105
+ assert result is True
106
+ mock_run.assert_called_once_with(
107
+ ["xdg-open", "cursor://test"], check=True, capture_output=True
108
+ )
109
+
110
+ @patch("subprocess.run")
111
+ def test_handles_subprocess_error(self, mock_run):
112
+ """Should return False when subprocess command fails."""
113
+ from subprocess import CalledProcessError
114
+
115
+ mock_run.side_effect = CalledProcessError(1, "open")
116
+
117
+ result = open_deeplink("cursor://test")
118
+
119
+ assert result is False
120
+
121
+ @patch("subprocess.run")
122
+ def test_handles_file_not_found(self, mock_run):
123
+ """Should return False when command is not found."""
124
+ mock_run.side_effect = FileNotFoundError()
125
+
126
+ result = open_deeplink("cursor://test")
127
+
128
+ assert result is False
129
+
130
+
131
+ class TestInstallCursor:
132
+ """Test install_cursor function."""
133
+
134
+ @patch("fastmcp.cli.install.cursor.open_deeplink")
135
+ @patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
136
+ @patch("fastmcp.cli.install.cursor.print")
137
+ def test_successful_installation(
138
+ self, mock_print, mock_generate_deeplink, mock_open_deeplink
139
+ ):
140
+ """Should successfully install when deeplink opens."""
141
+ mock_generate_deeplink.return_value = "cursor://test-deeplink"
142
+ mock_open_deeplink.return_value = True
143
+
144
+ result = install_cursor(Path("server.py"), None, "test-server")
145
+
146
+ assert result is True
147
+ mock_generate_deeplink.assert_called_once()
148
+ mock_open_deeplink.assert_called_once_with("cursor://test-deeplink")
149
+ mock_print.assert_called_once()
150
+ # Check that the success message was printed
151
+ assert "Opening Cursor to install" in str(mock_print.call_args)
152
+
153
+ @patch("fastmcp.cli.install.cursor.open_deeplink")
154
+ @patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
155
+ @patch("fastmcp.cli.install.cursor.print")
156
+ def test_fallback_when_deeplink_fails(
157
+ self, mock_print, mock_generate_deeplink, mock_open_deeplink
158
+ ):
159
+ """Should provide manual link when deeplink fails to open."""
160
+ mock_generate_deeplink.return_value = "cursor://test-deeplink"
161
+ mock_open_deeplink.return_value = False
162
+
163
+ result = install_cursor(Path("server.py"), None, "test-server")
164
+
165
+ assert result is True
166
+ assert mock_print.call_count == 2
167
+ # Check that both error and manual link messages were printed
168
+ print_calls = [str(call) for call in mock_print.call_args_list]
169
+ assert any(
170
+ "Could not open Cursor automatically" in call for call in print_calls
171
+ )
172
+ assert any("Please open this link" in call for call in print_calls)
173
+
174
+ @patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
175
+ @patch("fastmcp.cli.install.cursor.print")
176
+ def test_handles_deeplink_generation_error(
177
+ self, mock_print, mock_generate_deeplink
178
+ ):
179
+ """Should return False when deeplink generation fails."""
180
+ mock_generate_deeplink.side_effect = Exception("Test error")
181
+
182
+ result = install_cursor(Path("server.py"), None, "test-server")
183
+
184
+ assert result is False
185
+ mock_print.assert_called_once()
186
+ assert "Failed to generate Cursor deeplink" in str(mock_print.call_args)
187
+
188
+ @patch("fastmcp.cli.install.cursor.open_deeplink")
189
+ @patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
190
+ def test_builds_correct_server_config(
191
+ self, mock_generate_deeplink, mock_open_deeplink
192
+ ):
193
+ """Should build correct server configuration with all options."""
194
+ mock_generate_deeplink.return_value = "cursor://test"
195
+ mock_open_deeplink.return_value = True
196
+
197
+ install_cursor(
198
+ file=Path("server.py"),
199
+ server_object="custom_server",
200
+ name="test-server",
201
+ with_editable=Path("/path/to/editable"),
202
+ with_packages=["pandas", "requests"],
203
+ env_vars={"API_KEY": "secret", "DEBUG": "true"},
204
+ )
205
+
206
+ # Check that generate_cursor_deeplink was called with correct config
207
+ call_args = mock_generate_deeplink.call_args
208
+ server_name, server_config = call_args[0]
209
+
210
+ assert server_name == "test-server"
211
+ assert server_config.command == "uv"
212
+ assert "run" in server_config.args
213
+ assert "--with" in server_config.args
214
+ assert "fastmcp" in server_config.args
215
+ assert "pandas" in server_config.args
216
+ assert "requests" in server_config.args
217
+ assert "--with-editable" in server_config.args
218
+ assert str(Path("/path/to/editable")) in server_config.args
219
+ assert "fastmcp" in server_config.args
220
+ assert "run" in server_config.args
221
+ assert server_config.env == {"API_KEY": "secret", "DEBUG": "true"}
222
+
223
+ @patch("fastmcp.cli.install.cursor.open_deeplink")
224
+ @patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
225
+ def test_resolves_absolute_paths(self, mock_generate_deeplink, mock_open_deeplink):
226
+ """Should resolve server spec to absolute path."""
227
+ mock_generate_deeplink.return_value = "cursor://test"
228
+ mock_open_deeplink.return_value = True
229
+
230
+ install_cursor(Path("server.py"), None, "test-server")
231
+
232
+ call_args = mock_generate_deeplink.call_args
233
+ _, server_config = call_args[0]
234
+
235
+ # Find the server spec after "fastmcp run"
236
+ server_spec_in_args = None
237
+ for i, arg in enumerate(server_config.args):
238
+ if (
239
+ arg == "fastmcp"
240
+ and i + 2 < len(server_config.args)
241
+ and server_config.args[i + 1] == "run"
242
+ ):
243
+ server_spec_in_args = server_config.args[i + 2]
244
+ break
245
+
246
+ assert server_spec_in_args is not None
247
+ assert str(Path("server.py").resolve()) in server_spec_in_args
248
+
249
+ @patch("fastmcp.cli.install.cursor.open_deeplink")
250
+ @patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
251
+ def test_handles_server_spec_with_object(
252
+ self, mock_generate_deeplink, mock_open_deeplink
253
+ ):
254
+ """Should correctly handle server spec with object notation."""
255
+ mock_generate_deeplink.return_value = "cursor://test"
256
+ mock_open_deeplink.return_value = True
257
+
258
+ install_cursor(Path("server.py"), "custom_object", "test-server")
259
+
260
+ call_args = mock_generate_deeplink.call_args
261
+ _, server_config = call_args[0]
262
+
263
+ # Find the server spec after "fastmcp run"
264
+ server_spec_in_args = None
265
+ for i, arg in enumerate(server_config.args):
266
+ if (
267
+ arg == "fastmcp"
268
+ and i + 2 < len(server_config.args)
269
+ and server_config.args[i + 1] == "run"
270
+ ):
271
+ server_spec_in_args = server_config.args[i + 2]
272
+ break
273
+
274
+ assert server_spec_in_args is not None
275
+ assert ":custom_object" in server_spec_in_args
276
+ assert str(Path("server.py").resolve()) in server_spec_in_args