Add Claude Code install integration (#1053)

* Add Cursor support

* Use url-safe encoding

* Add claude code integration

* Delete test_install_dependencies.py

* Fix windows tests
This commit is contained in:
Jeremiah Lowin 2025-07-05 21:23:47 -04:00 committed by GitHub
commit 84f0229acc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 788 additions and 38 deletions

View file

@ -1,24 +1,26 @@
---
title: Claude Code + FastMCP
sidebarTitle: Claude Code
description: Connect FastMCP servers to Claude Code
description: Install and use FastMCP servers in Claude Code
icon: message-smile
tag: NEW
---
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.
import { VersionBadge } from "/snippets/version-badge.mdx"
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.
<Note>
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.
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).
</Note>
<Tip>
Claude Code provides built-in MCP management commands to easily add, configure, and authenticate your FastMCP servers.
</Tip>
## Requirements
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.
## Create a Server
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.
The examples in this guide will use the following simple dice-rolling server, saved as `server.py`.
```python server.py
import random
@ -32,29 +34,101 @@ def roll_dice(n_dice: int) -> list[int]:
return [random.randint(1, 6) for _ in range(n_dice)]
if __name__ == "__main__":
mcp.run(transport="http", port=8000)
mcp.run()
```
## Connect to Claude Code
## Install the Server
Start your server and add it to Claude Code:
### FastMCP CLI
<VersionBadge version="2.10.3" />
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.
```bash
# Start your server first
python server.py
fastmcp install claude-code server.py
```
Then add it to Claude Code:
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:
```bash
claude mcp add dice --transport http http://localhost:8000/mcp/
# These are equivalent if your server object is named 'mcp'
fastmcp install claude-code server.py
fastmcp install claude-code server.py:mcp
# Use explicit object name if your server has a different name
fastmcp install claude-code server.py:my_custom_server
```
## Using Your Server
The command will automatically configure the server with Claude Code's `claude mcp add` command.
Once connected, Claude Code will automatically discover and use your server's tools when relevant:
#### Dependencies
```
Roll some dice for me
If your server has dependencies, include them with the `--with` flag:
```bash
fastmcp install claude-code server.py --with pandas --with requests
```
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`.
Alternatively, you can specify dependencies directly in your server code:
```python server.py
from fastmcp import FastMCP
mcp = FastMCP(
name="Dice Roller",
dependencies=["pandas", "requests"]
)
```
#### Environment Variables
If your server needs environment variables (like API keys), you must include them:
```bash
fastmcp install claude-code server.py --name "Weather Server" \
--env-var API_KEY=your-api-key \
--env-var DEBUG=true
```
Or load them from a `.env` file:
```bash
fastmcp install claude-code server.py --name "Weather Server" --env-file .env
```
<Warning>
**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.
</Warning>
### Manual Configuration
For more control over the configuration, you can manually use Claude Code's built-in MCP management commands:
```bash
# Add a server with custom configuration
claude mcp add dice-roller -- uv run --with fastmcp fastmcp run server.py
# Add with environment variables
claude mcp add weather-server -e API_KEY=secret -e DEBUG=true -- uv run --with fastmcp fastmcp run server.py
# Add with specific scope (local, user, or project)
claude mcp add my-server --scope user -- uv run --with fastmcp fastmcp run server.py
```
## Using the Server
Once your server is installed, you can start using your FastMCP server with Claude Code.
Try asking Claude something like:
> "Roll some dice for me"
Claude will automatically detect your `roll_dice` tool and use it to fulfill your request, returning something like:
> I'll roll some dice for you! Here are your results: [4, 2, 6]
>
> You rolled three dice and got a 4, a 2, and a 6!
Claude Code can now access all the tools, resources, and prompts you've defined in your FastMCP server.
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`.

View file

@ -148,10 +148,12 @@ fastmcp dev server.py -e . --with pandas --with matplotlib
Install a MCP server in MCP client applications. FastMCP currently supports the following clients:
- **Claude Code** - Installs via Claude Code's built-in MCP management system
- **Claude Desktop** - Installs via direct configuration file modification
- **Cursor** - Installs via deeplink that opens Cursor for user confirmation
```bash
fastmcp install claude-code server.py
fastmcp install claude-desktop server.py
fastmcp install cursor server.py
```
@ -195,6 +197,9 @@ fastmcp install claude-desktop server.py:my_server
# With custom name and dependencies
fastmcp install claude-desktop server.py:my_server -n "My Analysis Server" --with pandas
# Install in Claude Code with environment variables
fastmcp install claude-code server.py --env-var API_KEY=secret --env-var DEBUG=true
# Install in Cursor with environment variables
fastmcp install cursor server.py --env-var API_KEY=secret --env-var DEBUG=true

View file

@ -0,0 +1,118 @@
"""Claude Code integration for FastMCP install."""
from __future__ import annotations
import subprocess
from pathlib import Path
from rich import print
from fastmcp.utilities.logging import get_logger
logger = get_logger(__name__)
def find_claude_command() -> str | None:
"""Find the Claude Code CLI command."""
# Check the default installation location
default_path = Path.home() / ".claude" / "local" / "claude"
if default_path.exists():
try:
result = subprocess.run(
[str(default_path), "--version"],
check=True,
capture_output=True,
text=True,
)
if "Claude Code" in result.stdout:
return str(default_path)
except (subprocess.CalledProcessError, FileNotFoundError):
pass
return None
def check_claude_code_available() -> bool:
"""Check if Claude Code CLI is available."""
return find_claude_command() is not None
def install_claude_code(
file: Path,
server_object: str | None,
name: str,
*,
with_editable: Path | None = None,
with_packages: list[str] | None = None,
env_vars: dict[str, str] | None = None,
) -> bool:
"""Install FastMCP server in Claude Code.
Args:
file: Path to the server file
server_object: Optional server object name (for :object suffix)
name: Name for the server in Claude Code
with_editable: Optional directory to install in editable mode
with_packages: Optional list of additional packages to install
env_vars: Optional dictionary of environment variables
Returns:
True if installation was successful, False otherwise
"""
# Check if Claude Code CLI is available
claude_cmd = find_claude_command()
if not claude_cmd:
print(
"[red]Claude Code CLI not found.[/red]\n"
"[blue]Please ensure Claude Code is installed. Try running 'claude --version' to verify.[/blue]"
)
return False
# Build uv run command
args = ["run"]
# Collect all packages in a set to deduplicate
packages = {"fastmcp"}
if with_packages:
packages.update(pkg for pkg in with_packages if pkg)
# Add all packages with --with
for pkg in sorted(packages):
args.extend(["--with", pkg])
if with_editable:
args.extend(["--with-editable", str(with_editable)])
# Build server spec from parsed components
if server_object:
server_spec = f"{file.resolve()}:{server_object}"
else:
server_spec = str(file.resolve())
# Add fastmcp run command
args.extend(["fastmcp", "run", server_spec])
# Build claude mcp add command
cmd_parts = [claude_cmd, "mcp", "add"]
# Add environment variables if specified (before the name and command)
if env_vars:
for key, value in env_vars.items():
cmd_parts.extend(["-e", f"{key}={value}"])
# Add server name and command
cmd_parts.extend([name, "--"])
cmd_parts.extend(["uv"] + args)
try:
# Run the claude mcp add command
subprocess.run(cmd_parts, check=True, capture_output=True, text=True)
return True
except subprocess.CalledProcessError as e:
print(
f"[red]Failed to install '[bold]{name}[/bold]' in Claude Code: {e.stderr.strip() if e.stderr else str(e)}[/red]"
)
return False
except Exception as e:
print(f"[red]Failed to install '[bold]{name}[/bold]' in Claude Code: {e}[/red]")
return False

View file

@ -33,7 +33,8 @@ def get_claude_config_path() -> Path | None:
def install_claude_desktop(
server_spec: str,
file: Path,
server_object: str | None,
name: str,
*,
with_editable: Path | None = None,
@ -43,7 +44,8 @@ def install_claude_desktop(
"""Install FastMCP server in Claude Desktop.
Args:
server_spec: Path to the server file, optionally with :object suffix
file: Path to the server file
server_object: Optional server object name (for :object suffix)
name: Name for the server in Claude's config
with_editable: Optional directory to install in editable mode
with_packages: Optional list of additional packages to install
@ -77,13 +79,11 @@ def install_claude_desktop(
if with_editable:
args.extend(["--with-editable", str(with_editable)])
# Convert file path to absolute before adding to command
# Split off any :object suffix first
if ":" in server_spec:
file_path, server_object = server_spec.rsplit(":", 1)
server_spec = f"{Path(file_path).resolve()}:{server_object}"
# Build server spec from parsed components
if server_object:
server_spec = f"{file.resolve()}:{server_object}"
else:
server_spec = str(Path(server_spec).resolve())
server_spec = str(file.resolve())
# Add fastmcp run command
args.extend(["fastmcp", "run", server_spec])

View file

@ -64,7 +64,8 @@ def open_deeplink(deeplink: str) -> bool:
def install_cursor(
server_spec: str,
file: Path,
server_object: str | None,
name: str,
*,
with_editable: Path | None = None,
@ -74,7 +75,8 @@ def install_cursor(
"""Install FastMCP server in Cursor.
Args:
server_spec: Path to the server file, optionally with :object suffix
file: Path to the server file
server_object: Optional server object name (for :object suffix)
name: Name for the server in Cursor's config
with_editable: Optional directory to install in editable mode
with_packages: Optional list of additional packages to install
@ -98,13 +100,11 @@ def install_cursor(
if with_editable:
args.extend(["--with-editable", str(with_editable)])
# Convert file path to absolute before adding to command
# Split off any :object suffix first
if ":" in server_spec:
file_path, server_object = server_spec.rsplit(":", 1)
server_spec = f"{Path(file_path).resolve()}:{server_object}"
# Build server spec from parsed components
if server_object:
server_spec = f"{file.resolve()}:{server_object}"
else:
server_spec = str(Path(server_spec).resolve())
server_spec = str(file.resolve())
# Add fastmcp run command
args.extend(["fastmcp", "run", server_spec])

View file

@ -14,6 +14,7 @@ from rich import print
from fastmcp.cli.run import import_server, parse_file_path
from fastmcp.utilities.logging import get_logger
from .claude_code import install_claude_code
from .claude_desktop import install_claude_desktop
from .cursor import install_cursor
@ -23,6 +24,7 @@ logger = get_logger(__name__)
class Client(str, Enum):
"""Supported MCP clients."""
CLAUDE_CODE = "claude-code"
CLAUDE_DESKTOP = "claude-desktop"
CURSOR = "cursor"
@ -142,9 +144,19 @@ def install(
env_dict[key] = value
# Route to appropriate installer
if client == Client.CLAUDE_DESKTOP:
if client == Client.CLAUDE_CODE:
success = install_claude_code(
file=file,
server_object=server_object,
name=name,
with_editable=with_editable,
with_packages=with_packages,
env_vars=env_dict,
)
elif client == Client.CLAUDE_DESKTOP:
success = install_claude_desktop(
server_spec=server_spec,
file=file,
server_object=server_object,
name=name,
with_editable=with_editable,
with_packages=with_packages,
@ -152,7 +164,8 @@ def install(
)
elif client == Client.CURSOR:
success = install_cursor(
server_spec=server_spec,
file=file,
server_object=server_object,
name=name,
with_editable=with_editable,
with_packages=with_packages,
@ -160,7 +173,7 @@ def install(
)
else:
print(
f"[red bold]Unknown client: {client!r}[/red bold]. Supported clients: [bold]{Client.CLAUDE_DESKTOP}[/bold], [bold]{Client.CURSOR}[/bold]"
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]"
)
raise typer.Exit(1)

View file

@ -0,0 +1,264 @@
"""Tests for Claude Code CLI integration."""
from pathlib import Path
from unittest.mock import MagicMock, patch
from fastmcp.cli.install.claude_code import (
check_claude_code_available,
find_claude_command,
install_claude_code,
)
class TestFindClaudeCommand:
"""Test find_claude_command function."""
@patch("subprocess.run")
@patch("pathlib.Path.exists")
def test_finds_command_in_default_location(self, mock_exists, mock_run):
"""Should find claude in default installation location."""
mock_exists.return_value = True
mock_run.return_value = MagicMock(stdout="1.0.43 (Claude Code)")
result = find_claude_command()
expected_path = str(Path.home() / ".claude" / "local" / "claude")
assert result == expected_path
mock_run.assert_called_once_with(
[expected_path, "--version"], check=True, capture_output=True, text=True
)
@patch("subprocess.run")
@patch("pathlib.Path.exists")
def test_rejects_non_claude_code_binary(self, mock_exists, mock_run):
"""Should reject binary that isn't Claude Code."""
mock_exists.return_value = True
mock_run.return_value = MagicMock(stdout="Some other claude 1.0.0")
result = find_claude_command()
assert result is None
@patch("subprocess.run")
@patch("pathlib.Path.exists")
def test_handles_subprocess_error(self, mock_exists, mock_run):
"""Should handle subprocess errors gracefully."""
from subprocess import CalledProcessError
mock_exists.return_value = True
mock_run.side_effect = CalledProcessError(1, "claude")
result = find_claude_command()
assert result is None
@patch("pathlib.Path.exists")
def test_no_command_found(self, mock_exists):
"""Should return None when binary doesn't exist."""
mock_exists.return_value = False
result = find_claude_command()
assert result is None
class TestCheckClaudeCodeAvailable:
"""Test check_claude_code_available function."""
@patch("fastmcp.cli.install.claude_code.find_claude_command")
def test_available_when_command_found(self, mock_find):
"""Should return True when claude command is found."""
mock_find.return_value = "/usr/local/bin/claude"
result = check_claude_code_available()
assert result is True
@patch("fastmcp.cli.install.claude_code.find_claude_command")
def test_not_available_when_command_not_found(self, mock_find):
"""Should return False when claude command is not found."""
mock_find.return_value = None
result = check_claude_code_available()
assert result is False
class TestInstallClaudeCode:
"""Test install_claude_code function."""
@patch("fastmcp.cli.install.claude_code.find_claude_command")
@patch("fastmcp.cli.install.claude_code.print")
def test_fails_when_claude_not_found(self, mock_print, mock_find):
"""Should return False and print error when Claude Code CLI not found."""
mock_find.return_value = None
result = install_claude_code(Path("server.py"), None, "test-server")
assert result is False
mock_print.assert_called_once()
assert "Claude Code CLI not found" in str(mock_print.call_args)
@patch("fastmcp.cli.install.claude_code.find_claude_command")
@patch("subprocess.run")
def test_successful_installation(self, mock_run, mock_find):
"""Should successfully install when command succeeds."""
mock_find.return_value = "/usr/local/bin/claude"
mock_run.return_value = MagicMock()
result = install_claude_code(Path("server.py"), None, "test-server")
assert result is True
mock_run.assert_called_once()
# Check the command that was run
call_args = mock_run.call_args[0][0]
assert call_args[0] == "/usr/local/bin/claude"
assert "mcp" in call_args
assert "add" in call_args
assert "test-server" in call_args
assert "--" in call_args
assert "uv" in call_args
@patch("fastmcp.cli.install.claude_code.find_claude_command")
@patch("subprocess.run")
@patch("fastmcp.cli.install.claude_code.print")
def test_handles_subprocess_error(self, mock_print, mock_run, mock_find):
"""Should handle subprocess errors and return False."""
from subprocess import CalledProcessError
mock_find.return_value = "/usr/local/bin/claude"
mock_run.side_effect = CalledProcessError(
1, "claude", stderr="Permission denied"
)
result = install_claude_code(Path("server.py"), None, "test-server")
assert result is False
mock_print.assert_called_once()
assert "Failed to install" in str(mock_print.call_args)
assert "Permission denied" in str(mock_print.call_args)
@patch("fastmcp.cli.install.claude_code.find_claude_command")
@patch("subprocess.run")
def test_builds_correct_command_with_options(self, mock_run, mock_find):
"""Should build correct command with all options."""
mock_find.return_value = "/usr/local/bin/claude"
mock_run.return_value = MagicMock()
install_claude_code(
file=Path("server.py"),
server_object="custom_server",
name="test-server",
with_editable=Path("/path/to/editable"),
with_packages=["pandas", "requests"],
env_vars={"API_KEY": "secret", "DEBUG": "true"},
)
# Check the command that was run
call_args = mock_run.call_args[0][0]
# Should have claude command
assert call_args[0] == "/usr/local/bin/claude"
assert "mcp" in call_args
assert "add" in call_args
# Should have environment variables
assert "-e" in call_args
env_vars = []
for i, arg in enumerate(call_args):
if arg == "-e" and i + 1 < len(call_args):
env_vars.append(call_args[i + 1])
assert "API_KEY=secret" in env_vars
assert "DEBUG=true" in env_vars
# Should have server name
assert "test-server" in call_args
# Should have separator
assert "--" in call_args
# Should have uv command with packages
assert "uv" in call_args
assert "run" in call_args
assert "--with" in call_args
assert "fastmcp" in call_args
assert "pandas" in call_args
assert "requests" in call_args
assert "--with-editable" in call_args
assert str(Path("/path/to/editable")) in call_args
@patch("fastmcp.cli.install.claude_code.find_claude_command")
@patch("subprocess.run")
def test_resolves_absolute_paths(self, mock_run, mock_find):
"""Should resolve server spec to absolute path."""
mock_find.return_value = "/usr/local/bin/claude"
mock_run.return_value = MagicMock()
install_claude_code(Path("server.py"), None, "test-server")
call_args = mock_run.call_args[0][0]
# Find the server spec after "fastmcp run"
server_spec_in_args = None
for i, arg in enumerate(call_args):
if (
arg == "fastmcp"
and i + 2 < len(call_args)
and call_args[i + 1] == "run"
):
server_spec_in_args = call_args[i + 2]
break
assert server_spec_in_args is not None
assert str(Path("server.py").resolve()) in server_spec_in_args
@patch("fastmcp.cli.install.claude_code.find_claude_command")
@patch("subprocess.run")
def test_handles_server_spec_with_object(self, mock_run, mock_find):
"""Should correctly handle server spec with object notation."""
mock_find.return_value = "/usr/local/bin/claude"
mock_run.return_value = MagicMock()
install_claude_code(Path("server.py"), "custom_object", "test-server")
call_args = mock_run.call_args[0][0]
# Find the server spec after "fastmcp run"
server_spec_in_args = None
for i, arg in enumerate(call_args):
if (
arg == "fastmcp"
and i + 2 < len(call_args)
and call_args[i + 1] == "run"
):
server_spec_in_args = call_args[i + 2]
break
assert server_spec_in_args is not None
assert ":custom_object" in server_spec_in_args
assert str(Path("server.py").resolve()) in server_spec_in_args
@patch("fastmcp.cli.install.claude_code.find_claude_command")
@patch("subprocess.run")
def test_deduplicates_packages(self, mock_run, mock_find):
"""Should deduplicate packages in the command."""
mock_find.return_value = "/usr/local/bin/claude"
mock_run.return_value = MagicMock()
install_claude_code(
file=Path("server.py"),
server_object=None,
name="test-server",
with_packages=["pandas", "fastmcp", "pandas"], # duplicates
)
call_args = mock_run.call_args[0][0]
# Count occurrences of pandas
pandas_count = sum(1 for arg in call_args if arg == "pandas")
fastmcp_count = sum(1 for arg in call_args if arg == "fastmcp")
# Should only appear once each for the package (fastmcp appears twice: once as package, once as command)
assert pandas_count == 1
assert fastmcp_count == 2 # Once in --with fastmcp, once in fastmcp run

276
tests/cli/test_cursor.py Normal file
View file

@ -0,0 +1,276 @@
"""Tests for Cursor CLI integration."""
import base64
import json
from pathlib import Path
from unittest.mock import patch
from fastmcp.cli.install.cursor import (
generate_cursor_deeplink,
install_cursor,
open_deeplink,
)
from fastmcp.mcp_config import StdioMCPServer
class TestGenerateCursorDeeplink:
"""Test generate_cursor_deeplink function."""
def test_generates_valid_deeplink(self):
"""Should generate a valid Cursor deeplink with base64 encoded config."""
server_config = StdioMCPServer(
command="uv",
args=["run", "--with", "fastmcp", "fastmcp", "run", "server.py"],
env={"API_KEY": "secret"},
)
deeplink = generate_cursor_deeplink("test-server", server_config)
assert deeplink.startswith("cursor://anysphere.cursor-deeplink/mcp/install?")
assert "name=test-server" in deeplink
assert "config=" in deeplink
def test_config_is_url_safe_base64(self):
"""Should use URL-safe base64 encoding for the config."""
server_config = StdioMCPServer(
command="test",
args=["arg1", "arg2"],
)
deeplink = generate_cursor_deeplink("test", server_config)
# Extract the config parameter
config_param = deeplink.split("config=")[1]
# Should be decodable as URL-safe base64
decoded = base64.urlsafe_b64decode(config_param.encode())
config_data = json.loads(decoded)
assert config_data["command"] == "test"
assert config_data["args"] == ["arg1", "arg2"]
def test_excludes_none_values(self):
"""Should exclude None values from the configuration."""
server_config = StdioMCPServer(
command="test",
args=["arg1"],
timeout=None, # This should be excluded
)
deeplink = generate_cursor_deeplink("test", server_config)
config_param = deeplink.split("config=")[1]
decoded = base64.urlsafe_b64decode(config_param.encode())
config_data = json.loads(decoded)
assert "timeout" not in config_data
class TestOpenDeeplink:
"""Test open_deeplink function."""
@patch("subprocess.run")
@patch("fastmcp.cli.install.cursor.sys.platform", "darwin")
def test_opens_on_macos(self, mock_run):
"""Should use 'open' command on macOS."""
mock_run.return_value = None
result = open_deeplink("cursor://test")
assert result is True
mock_run.assert_called_once_with(
["open", "cursor://test"], check=True, capture_output=True
)
@patch("subprocess.run")
@patch("fastmcp.cli.install.cursor.sys.platform", "win32")
def test_opens_on_windows(self, mock_run):
"""Should use 'start' command on Windows."""
mock_run.return_value = None
result = open_deeplink("cursor://test")
assert result is True
mock_run.assert_called_once_with(
["start", "cursor://test"], shell=True, check=True, capture_output=True
)
@patch("subprocess.run")
@patch("fastmcp.cli.install.cursor.sys.platform", "linux")
def test_opens_on_linux(self, mock_run):
"""Should use 'xdg-open' command on Linux."""
mock_run.return_value = None
result = open_deeplink("cursor://test")
assert result is True
mock_run.assert_called_once_with(
["xdg-open", "cursor://test"], check=True, capture_output=True
)
@patch("subprocess.run")
def test_handles_subprocess_error(self, mock_run):
"""Should return False when subprocess command fails."""
from subprocess import CalledProcessError
mock_run.side_effect = CalledProcessError(1, "open")
result = open_deeplink("cursor://test")
assert result is False
@patch("subprocess.run")
def test_handles_file_not_found(self, mock_run):
"""Should return False when command is not found."""
mock_run.side_effect = FileNotFoundError()
result = open_deeplink("cursor://test")
assert result is False
class TestInstallCursor:
"""Test install_cursor function."""
@patch("fastmcp.cli.install.cursor.open_deeplink")
@patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
@patch("fastmcp.cli.install.cursor.print")
def test_successful_installation(
self, mock_print, mock_generate_deeplink, mock_open_deeplink
):
"""Should successfully install when deeplink opens."""
mock_generate_deeplink.return_value = "cursor://test-deeplink"
mock_open_deeplink.return_value = True
result = install_cursor(Path("server.py"), None, "test-server")
assert result is True
mock_generate_deeplink.assert_called_once()
mock_open_deeplink.assert_called_once_with("cursor://test-deeplink")
mock_print.assert_called_once()
# Check that the success message was printed
assert "Opening Cursor to install" in str(mock_print.call_args)
@patch("fastmcp.cli.install.cursor.open_deeplink")
@patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
@patch("fastmcp.cli.install.cursor.print")
def test_fallback_when_deeplink_fails(
self, mock_print, mock_generate_deeplink, mock_open_deeplink
):
"""Should provide manual link when deeplink fails to open."""
mock_generate_deeplink.return_value = "cursor://test-deeplink"
mock_open_deeplink.return_value = False
result = install_cursor(Path("server.py"), None, "test-server")
assert result is True
assert mock_print.call_count == 2
# Check that both error and manual link messages were printed
print_calls = [str(call) for call in mock_print.call_args_list]
assert any(
"Could not open Cursor automatically" in call for call in print_calls
)
assert any("Please open this link" in call for call in print_calls)
@patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
@patch("fastmcp.cli.install.cursor.print")
def test_handles_deeplink_generation_error(
self, mock_print, mock_generate_deeplink
):
"""Should return False when deeplink generation fails."""
mock_generate_deeplink.side_effect = Exception("Test error")
result = install_cursor(Path("server.py"), None, "test-server")
assert result is False
mock_print.assert_called_once()
assert "Failed to generate Cursor deeplink" in str(mock_print.call_args)
@patch("fastmcp.cli.install.cursor.open_deeplink")
@patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
def test_builds_correct_server_config(
self, mock_generate_deeplink, mock_open_deeplink
):
"""Should build correct server configuration with all options."""
mock_generate_deeplink.return_value = "cursor://test"
mock_open_deeplink.return_value = True
install_cursor(
file=Path("server.py"),
server_object="custom_server",
name="test-server",
with_editable=Path("/path/to/editable"),
with_packages=["pandas", "requests"],
env_vars={"API_KEY": "secret", "DEBUG": "true"},
)
# Check that generate_cursor_deeplink was called with correct config
call_args = mock_generate_deeplink.call_args
server_name, server_config = call_args[0]
assert server_name == "test-server"
assert server_config.command == "uv"
assert "run" in server_config.args
assert "--with" in server_config.args
assert "fastmcp" in server_config.args
assert "pandas" in server_config.args
assert "requests" in server_config.args
assert "--with-editable" in server_config.args
assert str(Path("/path/to/editable")) in server_config.args
assert "fastmcp" in server_config.args
assert "run" in server_config.args
assert server_config.env == {"API_KEY": "secret", "DEBUG": "true"}
@patch("fastmcp.cli.install.cursor.open_deeplink")
@patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
def test_resolves_absolute_paths(self, mock_generate_deeplink, mock_open_deeplink):
"""Should resolve server spec to absolute path."""
mock_generate_deeplink.return_value = "cursor://test"
mock_open_deeplink.return_value = True
install_cursor(Path("server.py"), None, "test-server")
call_args = mock_generate_deeplink.call_args
_, server_config = call_args[0]
# Find the server spec after "fastmcp run"
server_spec_in_args = None
for i, arg in enumerate(server_config.args):
if (
arg == "fastmcp"
and i + 2 < len(server_config.args)
and server_config.args[i + 1] == "run"
):
server_spec_in_args = server_config.args[i + 2]
break
assert server_spec_in_args is not None
assert str(Path("server.py").resolve()) in server_spec_in_args
@patch("fastmcp.cli.install.cursor.open_deeplink")
@patch("fastmcp.cli.install.cursor.generate_cursor_deeplink")
def test_handles_server_spec_with_object(
self, mock_generate_deeplink, mock_open_deeplink
):
"""Should correctly handle server spec with object notation."""
mock_generate_deeplink.return_value = "cursor://test"
mock_open_deeplink.return_value = True
install_cursor(Path("server.py"), "custom_object", "test-server")
call_args = mock_generate_deeplink.call_args
_, server_config = call_args[0]
# Find the server spec after "fastmcp run"
server_spec_in_args = None
for i, arg in enumerate(server_config.args):
if (
arg == "fastmcp"
and i + 2 < len(server_config.args)
and server_config.args[i + 1] == "run"
):
server_spec_in_args = server_config.args[i + 2]
break
assert server_spec_in_args is not None
assert ":custom_object" in server_spec_in_args
assert str(Path("server.py").resolve()) in server_spec_in_args