golf-mcp 0.1.9__py3-none-any.whl → 0.1.11__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of golf-mcp might be problematic. Click here for more details.
- golf/__init__.py +1 -1
- golf/auth/__init__.py +1 -1
- golf/auth/helpers.py +112 -2
- golf/cli/main.py +27 -14
- golf/commands/init.py +73 -62
- golf/core/builder.py +35 -12
- golf/core/builder_auth.py +31 -91
- golf/core/telemetry.py +57 -4
- golf/telemetry/instrumentation.py +511 -151
- {golf_mcp-0.1.9.dist-info → golf_mcp-0.1.11.dist-info}/METADATA +1 -1
- {golf_mcp-0.1.9.dist-info → golf_mcp-0.1.11.dist-info}/RECORD +15 -15
- {golf_mcp-0.1.9.dist-info → golf_mcp-0.1.11.dist-info}/WHEEL +1 -1
- {golf_mcp-0.1.9.dist-info → golf_mcp-0.1.11.dist-info}/entry_points.txt +0 -0
- {golf_mcp-0.1.9.dist-info → golf_mcp-0.1.11.dist-info}/licenses/LICENSE +0 -0
- {golf_mcp-0.1.9.dist-info → golf_mcp-0.1.11.dist-info}/top_level.txt +0 -0
golf/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = "0.1.
|
|
1
|
+
__version__ = "0.1.11"
|
golf/auth/__init__.py
CHANGED
|
@@ -11,7 +11,7 @@ from mcp.server.auth.settings import AuthSettings, ClientRegistrationOptions
|
|
|
11
11
|
|
|
12
12
|
from .provider import ProviderConfig
|
|
13
13
|
from .oauth import GolfOAuthProvider, create_callback_handler
|
|
14
|
-
from .helpers import get_access_token, get_provider_token, extract_token_from_header, get_api_key, set_api_key
|
|
14
|
+
from .helpers import get_access_token, get_provider_token, extract_token_from_header, get_api_key, set_api_key, debug_api_key_context
|
|
15
15
|
from .api_key import configure_api_key, get_api_key_config, is_api_key_configured
|
|
16
16
|
|
|
17
17
|
class AuthConfig:
|
golf/auth/helpers.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Helper functions for working with authentication in MCP context."""
|
|
2
2
|
|
|
3
|
-
from typing import Optional
|
|
3
|
+
from typing import Optional, Dict, Any
|
|
4
4
|
from contextvars import ContextVar
|
|
5
5
|
|
|
6
6
|
# Re-export get_access_token from the MCP SDK
|
|
@@ -94,4 +94,114 @@ def get_api_key() -> Optional[str]:
|
|
|
94
94
|
headers = {"Authorization": f"Bearer {api_key}"}
|
|
95
95
|
...
|
|
96
96
|
"""
|
|
97
|
-
|
|
97
|
+
# Try to get directly from HTTP request if available (FastMCP pattern)
|
|
98
|
+
try:
|
|
99
|
+
# This follows the FastMCP pattern for accessing HTTP requests
|
|
100
|
+
from fastmcp.server.dependencies import get_http_request
|
|
101
|
+
request = get_http_request()
|
|
102
|
+
|
|
103
|
+
if request and hasattr(request, 'state') and hasattr(request.state, 'api_key'):
|
|
104
|
+
api_key = request.state.api_key
|
|
105
|
+
return api_key
|
|
106
|
+
|
|
107
|
+
# Get the API key configuration
|
|
108
|
+
from golf.auth.api_key import get_api_key_config
|
|
109
|
+
api_key_config = get_api_key_config()
|
|
110
|
+
|
|
111
|
+
if api_key_config and request:
|
|
112
|
+
# Extract API key from headers
|
|
113
|
+
header_name = api_key_config.header_name
|
|
114
|
+
header_prefix = api_key_config.header_prefix
|
|
115
|
+
|
|
116
|
+
# Case-insensitive header lookup
|
|
117
|
+
api_key = None
|
|
118
|
+
for k, v in request.headers.items():
|
|
119
|
+
if k.lower() == header_name.lower():
|
|
120
|
+
api_key = v
|
|
121
|
+
break
|
|
122
|
+
|
|
123
|
+
# Strip prefix if configured
|
|
124
|
+
if api_key and header_prefix and api_key.startswith(header_prefix):
|
|
125
|
+
api_key = api_key[len(header_prefix):]
|
|
126
|
+
|
|
127
|
+
if api_key:
|
|
128
|
+
return api_key
|
|
129
|
+
except (ImportError, RuntimeError) as e:
|
|
130
|
+
# FastMCP not available or not in HTTP context
|
|
131
|
+
pass
|
|
132
|
+
except Exception as e:
|
|
133
|
+
pass
|
|
134
|
+
|
|
135
|
+
# Final fallback: environment variable (for development/testing)
|
|
136
|
+
import os
|
|
137
|
+
env_api_key = os.environ.get('API_KEY')
|
|
138
|
+
if env_api_key:
|
|
139
|
+
return env_api_key
|
|
140
|
+
|
|
141
|
+
return None
|
|
142
|
+
|
|
143
|
+
def get_api_key_from_request(request) -> Optional[str]:
|
|
144
|
+
"""Get the API key from a specific request object.
|
|
145
|
+
|
|
146
|
+
This is useful when you have direct access to the request object.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
request: The Starlette Request object
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
The API key if available, None otherwise
|
|
153
|
+
"""
|
|
154
|
+
# Check request state first (set by our middleware)
|
|
155
|
+
if hasattr(request, 'state') and hasattr(request.state, 'api_key'):
|
|
156
|
+
return request.state.api_key
|
|
157
|
+
|
|
158
|
+
# Fall back to context variable
|
|
159
|
+
return _current_api_key.get()
|
|
160
|
+
|
|
161
|
+
def debug_api_key_context() -> Dict[str, Any]:
|
|
162
|
+
"""Debug function to inspect API key context.
|
|
163
|
+
|
|
164
|
+
Returns a dictionary with debugging information about the current
|
|
165
|
+
API key context. Useful for troubleshooting authentication issues.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
Dictionary with debug information
|
|
169
|
+
"""
|
|
170
|
+
import asyncio
|
|
171
|
+
import sys
|
|
172
|
+
import os
|
|
173
|
+
|
|
174
|
+
debug_info = {
|
|
175
|
+
"context_var_value": _current_api_key.get(),
|
|
176
|
+
"has_async_task": False,
|
|
177
|
+
"task_id": None,
|
|
178
|
+
"main_module_has_storage": False,
|
|
179
|
+
"main_module_has_context": False,
|
|
180
|
+
"request_id_from_context": None,
|
|
181
|
+
"env_vars": {
|
|
182
|
+
"API_KEY": bool(os.environ.get('API_KEY')),
|
|
183
|
+
"GOLF_API_KEY_DEBUG": os.environ.get('GOLF_API_KEY_DEBUG', 'false')
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
try:
|
|
188
|
+
task = asyncio.current_task()
|
|
189
|
+
if task:
|
|
190
|
+
debug_info["has_async_task"] = True
|
|
191
|
+
debug_info["task_id"] = id(task)
|
|
192
|
+
except:
|
|
193
|
+
pass
|
|
194
|
+
|
|
195
|
+
try:
|
|
196
|
+
main_module = sys.modules.get('__main__')
|
|
197
|
+
if main_module:
|
|
198
|
+
debug_info["main_module_has_storage"] = hasattr(main_module, 'api_key_storage')
|
|
199
|
+
debug_info["main_module_has_context"] = hasattr(main_module, 'request_id_context')
|
|
200
|
+
|
|
201
|
+
if hasattr(main_module, 'request_id_context'):
|
|
202
|
+
request_id_context = getattr(main_module, 'request_id_context')
|
|
203
|
+
debug_info["request_id_from_context"] = request_id_context.get()
|
|
204
|
+
except:
|
|
205
|
+
pass
|
|
206
|
+
|
|
207
|
+
return debug_info
|
golf/cli/main.py
CHANGED
|
@@ -106,7 +106,7 @@ def build_dev(
|
|
|
106
106
|
if not project_root:
|
|
107
107
|
console.print("[bold red]Error: No GolfMCP project found in the current directory or any parent directory.[/bold red]")
|
|
108
108
|
console.print("Run 'golf init <project_name>' to create a new project.")
|
|
109
|
-
track_event("cli_build_failed", {"success": False, "environment": "dev"})
|
|
109
|
+
track_event("cli_build_failed", {"success": False, "environment": "dev", "error_type": "NoProjectFound", "error_message": "No GolfMCP project found"})
|
|
110
110
|
raise typer.Exit(code=1)
|
|
111
111
|
|
|
112
112
|
# Load settings from the found project
|
|
@@ -124,8 +124,10 @@ def build_dev(
|
|
|
124
124
|
build_project(project_root, settings, output_dir, build_env="dev", copy_env=True)
|
|
125
125
|
# Track successful build with environment
|
|
126
126
|
track_event("cli_build_success", {"success": True, "environment": "dev"})
|
|
127
|
-
except Exception:
|
|
128
|
-
|
|
127
|
+
except Exception as e:
|
|
128
|
+
error_type = type(e).__name__
|
|
129
|
+
error_message = str(e)
|
|
130
|
+
track_event("cli_build_failed", {"success": False, "environment": "dev", "error_type": error_type, "error_message": error_message})
|
|
129
131
|
raise
|
|
130
132
|
|
|
131
133
|
|
|
@@ -142,7 +144,7 @@ def build_prod(
|
|
|
142
144
|
if not project_root:
|
|
143
145
|
console.print("[bold red]Error: No GolfMCP project found in the current directory or any parent directory.[/bold red]")
|
|
144
146
|
console.print("Run 'golf init <project_name>' to create a new project.")
|
|
145
|
-
track_event("cli_build_failed", {"success": False, "environment": "prod"})
|
|
147
|
+
track_event("cli_build_failed", {"success": False, "environment": "prod", "error_type": "NoProjectFound", "error_message": "No GolfMCP project found"})
|
|
146
148
|
raise typer.Exit(code=1)
|
|
147
149
|
|
|
148
150
|
# Load settings from the found project
|
|
@@ -160,8 +162,10 @@ def build_prod(
|
|
|
160
162
|
build_project(project_root, settings, output_dir, build_env="prod", copy_env=False)
|
|
161
163
|
# Track successful build with environment
|
|
162
164
|
track_event("cli_build_success", {"success": True, "environment": "prod"})
|
|
163
|
-
except Exception:
|
|
164
|
-
|
|
165
|
+
except Exception as e:
|
|
166
|
+
error_type = type(e).__name__
|
|
167
|
+
error_message = str(e)
|
|
168
|
+
track_event("cli_build_failed", {"success": False, "environment": "prod", "error_type": error_type, "error_message": error_message})
|
|
165
169
|
raise
|
|
166
170
|
|
|
167
171
|
|
|
@@ -191,7 +195,7 @@ def run(
|
|
|
191
195
|
if not project_root:
|
|
192
196
|
console.print("[bold red]Error: No GolfMCP project found in the current directory or any parent directory.[/bold red]")
|
|
193
197
|
console.print("Run 'golf init <project_name>' to create a new project.")
|
|
194
|
-
track_event("cli_run_failed", {"success": False})
|
|
198
|
+
track_event("cli_run_failed", {"success": False, "error_type": "NoProjectFound", "error_message": "No GolfMCP project found"})
|
|
195
199
|
raise typer.Exit(code=1)
|
|
196
200
|
|
|
197
201
|
# Load settings from the found project
|
|
@@ -207,13 +211,20 @@ def run(
|
|
|
207
211
|
if not dist_dir.exists():
|
|
208
212
|
if build_first:
|
|
209
213
|
console.print(f"[yellow]Dist directory {dist_dir} not found. Building first...[/yellow]")
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
214
|
+
try:
|
|
215
|
+
# Build the project
|
|
216
|
+
from golf.commands.build import build_project
|
|
217
|
+
build_project(project_root, settings, dist_dir)
|
|
218
|
+
except Exception as e:
|
|
219
|
+
error_type = type(e).__name__
|
|
220
|
+
error_message = str(e)
|
|
221
|
+
console.print(f"[bold red]Error building project:[/bold red] {error_message}")
|
|
222
|
+
track_event("cli_run_failed", {"success": False, "error_type": f"BuildError.{error_type}", "error_message": error_message})
|
|
223
|
+
raise
|
|
213
224
|
else:
|
|
214
225
|
console.print(f"[bold red]Error: Dist directory {dist_dir} not found.[/bold red]")
|
|
215
226
|
console.print("Run 'golf build' first or use --build to build automatically.")
|
|
216
|
-
track_event("cli_run_failed", {"success": False})
|
|
227
|
+
track_event("cli_run_failed", {"success": False, "error_type": "DistNotFound", "error_message": "Dist directory not found"})
|
|
217
228
|
raise typer.Exit(code=1)
|
|
218
229
|
|
|
219
230
|
try:
|
|
@@ -231,13 +242,15 @@ def run(
|
|
|
231
242
|
if return_code == 0:
|
|
232
243
|
track_event("cli_run_success", {"success": True})
|
|
233
244
|
else:
|
|
234
|
-
track_event("cli_run_failed", {"success": False})
|
|
245
|
+
track_event("cli_run_failed", {"success": False, "error_type": "NonZeroExit", "error_message": f"Server exited with code {return_code}"})
|
|
235
246
|
|
|
236
247
|
# Exit with the same code as the server
|
|
237
248
|
if return_code != 0:
|
|
238
249
|
raise typer.Exit(code=return_code)
|
|
239
|
-
except Exception:
|
|
240
|
-
|
|
250
|
+
except Exception as e:
|
|
251
|
+
error_type = type(e).__name__
|
|
252
|
+
error_message = str(e)
|
|
253
|
+
track_event("cli_run_failed", {"success": False, "error_type": error_type, "error_message": error_message})
|
|
241
254
|
raise
|
|
242
255
|
|
|
243
256
|
|
golf/commands/init.py
CHANGED
|
@@ -9,7 +9,7 @@ from rich.console import Console
|
|
|
9
9
|
from rich.progress import Progress, SpinnerColumn, TextColumn
|
|
10
10
|
from rich.prompt import Confirm
|
|
11
11
|
|
|
12
|
-
from golf.core.telemetry import track_event
|
|
12
|
+
from golf.core.telemetry import track_event, track_command
|
|
13
13
|
|
|
14
14
|
console = Console()
|
|
15
15
|
|
|
@@ -26,72 +26,83 @@ def initialize_project(
|
|
|
26
26
|
output_dir: Directory where the project will be created
|
|
27
27
|
template: Template to use (basic or api_key)
|
|
28
28
|
"""
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
if
|
|
29
|
+
try:
|
|
30
|
+
# Validate template
|
|
31
|
+
valid_templates = ("basic", "api_key")
|
|
32
|
+
if template not in valid_templates:
|
|
33
|
+
console.print(f"[bold red]Error:[/bold red] Unknown template '{template}'")
|
|
34
|
+
console.print(f"Available templates: {', '.join(valid_templates)}")
|
|
35
|
+
track_command("init", success=False, error_type="InvalidTemplate", error_message=f"Unknown template: {template}")
|
|
36
|
+
return
|
|
37
|
+
|
|
38
|
+
# Check if directory exists
|
|
39
|
+
if output_dir.exists():
|
|
40
|
+
if not output_dir.is_dir():
|
|
41
|
+
console.print(
|
|
42
|
+
f"[bold red]Error:[/bold red] '{output_dir}' exists but is not a directory."
|
|
43
|
+
)
|
|
44
|
+
track_command("init", success=False, error_type="NotADirectory", error_message="Target exists but is not a directory")
|
|
45
|
+
return
|
|
46
|
+
|
|
47
|
+
# Check if directory is empty
|
|
48
|
+
if any(output_dir.iterdir()):
|
|
49
|
+
if not Confirm.ask(
|
|
50
|
+
f"Directory '{output_dir}' is not empty. Continue anyway?",
|
|
51
|
+
default=False,
|
|
52
|
+
):
|
|
53
|
+
console.print("Initialization cancelled.")
|
|
54
|
+
track_event("cli_init_cancelled", {"success": False})
|
|
55
|
+
return
|
|
56
|
+
else:
|
|
57
|
+
# Create the directory
|
|
58
|
+
output_dir.mkdir(parents=True)
|
|
59
|
+
|
|
60
|
+
# Find template directory within the installed package
|
|
61
|
+
import golf
|
|
62
|
+
package_init_file = Path(golf.__file__)
|
|
63
|
+
# The 'examples' directory is now inside the 'golf' package directory
|
|
64
|
+
# e.g. golf/examples/basic, so go up one from __init__.py to get to 'golf'
|
|
65
|
+
template_dir = package_init_file.parent / "examples" / template
|
|
66
|
+
|
|
67
|
+
if not template_dir.exists():
|
|
40
68
|
console.print(
|
|
41
|
-
f"[bold red]Error:[/bold red] '{
|
|
69
|
+
f"[bold red]Error:[/bold red] Could not find template '{template}'"
|
|
42
70
|
)
|
|
43
|
-
|
|
71
|
+
track_command("init", success=False, error_type="TemplateNotFound", error_message=f"Template directory not found: {template}")
|
|
44
72
|
return
|
|
45
73
|
|
|
46
|
-
#
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
# Create the directory
|
|
57
|
-
output_dir.mkdir(parents=True)
|
|
58
|
-
|
|
59
|
-
# Find template directory within the installed package
|
|
60
|
-
import golf
|
|
61
|
-
package_init_file = Path(golf.__file__)
|
|
62
|
-
# The 'examples' directory is now inside the 'golf' package directory
|
|
63
|
-
# e.g. golf/examples/basic, so go up one from __init__.py to get to 'golf'
|
|
64
|
-
template_dir = package_init_file.parent / "examples" / template
|
|
65
|
-
|
|
66
|
-
if not template_dir.exists():
|
|
67
|
-
console.print(
|
|
68
|
-
f"[bold red]Error:[/bold red] Could not find template '{template}'"
|
|
69
|
-
)
|
|
70
|
-
track_event("cli_init_failed", {"success": False})
|
|
71
|
-
return
|
|
72
|
-
|
|
73
|
-
# Copy template files
|
|
74
|
-
with Progress(
|
|
75
|
-
SpinnerColumn(),
|
|
76
|
-
TextColumn("[bold green]Creating project structure...[/bold green]"),
|
|
77
|
-
transient=True,
|
|
78
|
-
) as progress:
|
|
79
|
-
progress.add_task("copying", total=None)
|
|
74
|
+
# Copy template files
|
|
75
|
+
with Progress(
|
|
76
|
+
SpinnerColumn(),
|
|
77
|
+
TextColumn("[bold green]Creating project structure...[/bold green]"),
|
|
78
|
+
transient=True,
|
|
79
|
+
) as progress:
|
|
80
|
+
progress.add_task("copying", total=None)
|
|
81
|
+
|
|
82
|
+
# Copy directory structure
|
|
83
|
+
_copy_template(template_dir, output_dir, project_name)
|
|
80
84
|
|
|
81
|
-
#
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
85
|
+
# Create virtual environment
|
|
86
|
+
console.print("[bold green]Project initialized successfully![/bold green]")
|
|
87
|
+
console.print(f"\nTo get started, run:")
|
|
88
|
+
console.print(f" cd {output_dir.name}")
|
|
89
|
+
console.print(f" golf build dev")
|
|
90
|
+
|
|
91
|
+
# Track successful initialization
|
|
92
|
+
track_event("cli_init_success", {
|
|
93
|
+
"success": True,
|
|
94
|
+
"template": template
|
|
95
|
+
})
|
|
96
|
+
except Exception as e:
|
|
97
|
+
# Capture error details for telemetry
|
|
98
|
+
error_type = type(e).__name__
|
|
99
|
+
error_message = str(e)
|
|
100
|
+
|
|
101
|
+
console.print(f"[bold red]Error during initialization:[/bold red] {error_message}")
|
|
102
|
+
track_command("init", success=False, error_type=error_type, error_message=error_message)
|
|
103
|
+
|
|
104
|
+
# Re-raise to maintain existing behavior
|
|
105
|
+
raise
|
|
95
106
|
|
|
96
107
|
|
|
97
108
|
def _copy_template(source_dir: Path, target_dir: Path, project_name: str) -> None:
|
golf/core/builder.py
CHANGED
|
@@ -20,6 +20,7 @@ from golf.core.parser import (
|
|
|
20
20
|
from golf.core.transformer import transform_component
|
|
21
21
|
from golf.core.builder_auth import generate_auth_code, generate_auth_routes
|
|
22
22
|
from golf.auth import get_auth_config
|
|
23
|
+
from golf.auth.api_key import get_api_key_config
|
|
23
24
|
from golf.core.builder_telemetry import (
|
|
24
25
|
generate_telemetry_imports,
|
|
25
26
|
get_otel_dependencies
|
|
@@ -548,8 +549,7 @@ class CodeGenerator:
|
|
|
548
549
|
# Add imports section for different transport methods
|
|
549
550
|
if self.settings.transport == "sse":
|
|
550
551
|
imports.append("import uvicorn")
|
|
551
|
-
|
|
552
|
-
elif self.settings.transport != "stdio":
|
|
552
|
+
elif self.settings.transport in ["streamable-http", "http"]:
|
|
553
553
|
imports.append("import uvicorn")
|
|
554
554
|
|
|
555
555
|
# Get transport-specific configuration
|
|
@@ -735,12 +735,6 @@ class CodeGenerator:
|
|
|
735
735
|
server_code_lines.append(mcp_instance_line)
|
|
736
736
|
server_code_lines.append("")
|
|
737
737
|
|
|
738
|
-
# Add any post-init code from auth
|
|
739
|
-
post_init_code = []
|
|
740
|
-
if auth_components.get("has_auth") and auth_components.get("post_init_code"):
|
|
741
|
-
post_init_code.extend(auth_components["post_init_code"])
|
|
742
|
-
post_init_code.append("")
|
|
743
|
-
|
|
744
738
|
# Main entry point with transport-specific app initialization
|
|
745
739
|
main_code = [
|
|
746
740
|
"if __name__ == \"__main__\":",
|
|
@@ -764,16 +758,46 @@ class CodeGenerator:
|
|
|
764
758
|
|
|
765
759
|
# Transport-specific run methods
|
|
766
760
|
if self.settings.transport == "sse":
|
|
761
|
+
# Check if we need to add API key middleware for SSE
|
|
762
|
+
api_key_config = get_api_key_config()
|
|
763
|
+
if auth_components.get("has_auth") and api_key_config:
|
|
764
|
+
main_code.extend([
|
|
765
|
+
" # For SSE with API key auth, we need to get the app and add middleware",
|
|
766
|
+
" app = mcp.http_app(transport=\"sse\")",
|
|
767
|
+
" app.add_middleware(ApiKeyMiddleware)",
|
|
768
|
+
])
|
|
769
|
+
else:
|
|
770
|
+
main_code.extend([
|
|
771
|
+
" # For SSE, get the app to add middleware",
|
|
772
|
+
" app = mcp.http_app(transport=\"sse\")",
|
|
773
|
+
])
|
|
774
|
+
|
|
775
|
+
# Add OpenTelemetry middleware to the SSE app if enabled
|
|
776
|
+
if self.settings.opentelemetry_enabled:
|
|
777
|
+
main_code.extend([
|
|
778
|
+
" # Apply OpenTelemetry middleware to the SSE app",
|
|
779
|
+
" from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware",
|
|
780
|
+
" app = OpenTelemetryMiddleware(app)",
|
|
781
|
+
])
|
|
782
|
+
|
|
767
783
|
main_code.extend([
|
|
768
|
-
" #
|
|
769
|
-
"
|
|
784
|
+
" # Run with the configured app",
|
|
785
|
+
" uvicorn.run(app, host=host, port=port, log_level=\"info\")"
|
|
770
786
|
])
|
|
771
|
-
elif self.settings.transport
|
|
787
|
+
elif self.settings.transport in ["streamable-http", "http"]:
|
|
772
788
|
main_code.extend([
|
|
773
789
|
" # Create HTTP app and run with uvicorn",
|
|
774
790
|
" app = mcp.http_app()",
|
|
775
791
|
])
|
|
776
792
|
|
|
793
|
+
# Check if we need to add API key middleware
|
|
794
|
+
api_key_config = get_api_key_config()
|
|
795
|
+
if auth_components.get("has_auth") and api_key_config:
|
|
796
|
+
main_code.extend([
|
|
797
|
+
" # Add API key middleware",
|
|
798
|
+
" app.add_middleware(ApiKeyMiddleware)",
|
|
799
|
+
])
|
|
800
|
+
|
|
777
801
|
# Add OpenTelemetry middleware to the HTTP app if enabled
|
|
778
802
|
if self.settings.opentelemetry_enabled:
|
|
779
803
|
main_code.extend([
|
|
@@ -800,7 +824,6 @@ class CodeGenerator:
|
|
|
800
824
|
env_section +
|
|
801
825
|
auth_setup_code +
|
|
802
826
|
server_code_lines +
|
|
803
|
-
post_init_code +
|
|
804
827
|
component_registrations +
|
|
805
828
|
main_code
|
|
806
829
|
)
|
golf/core/builder_auth.py
CHANGED
|
@@ -145,7 +145,6 @@ def generate_api_key_auth_components(server_name: str, opentelemetry_enabled: bo
|
|
|
145
145
|
- setup_code: Auth setup code (middleware setup)
|
|
146
146
|
- fastmcp_args: Dict of arguments to add to FastMCP constructor
|
|
147
147
|
- has_auth: Whether auth is configured
|
|
148
|
-
- post_init_code: Code to run after FastMCP instance is created
|
|
149
148
|
"""
|
|
150
149
|
api_key_config = get_api_key_config()
|
|
151
150
|
if not api_key_config:
|
|
@@ -153,24 +152,35 @@ def generate_api_key_auth_components(server_name: str, opentelemetry_enabled: bo
|
|
|
153
152
|
"imports": [],
|
|
154
153
|
"setup_code": [],
|
|
155
154
|
"fastmcp_args": {},
|
|
156
|
-
"has_auth": False
|
|
157
|
-
"post_init_code": []
|
|
155
|
+
"has_auth": False
|
|
158
156
|
}
|
|
159
157
|
|
|
160
158
|
auth_imports = [
|
|
161
159
|
"# API key authentication setup",
|
|
162
|
-
"from golf.auth.
|
|
163
|
-
"from golf.auth
|
|
160
|
+
"from golf.auth.api_key import get_api_key_config, configure_api_key",
|
|
161
|
+
"from golf.auth import set_api_key",
|
|
164
162
|
"from starlette.middleware.base import BaseHTTPMiddleware",
|
|
165
163
|
"from starlette.requests import Request",
|
|
166
164
|
"from starlette.responses import JSONResponse",
|
|
165
|
+
"import os",
|
|
167
166
|
]
|
|
168
167
|
|
|
169
168
|
setup_code_lines = [
|
|
170
|
-
"#
|
|
169
|
+
"# Recreate API key configuration from pre_build.py",
|
|
170
|
+
f"configure_api_key(",
|
|
171
|
+
f" header_name={repr(api_key_config.header_name)},",
|
|
172
|
+
f" header_prefix={repr(api_key_config.header_prefix)},",
|
|
173
|
+
f" required={repr(api_key_config.required)}",
|
|
174
|
+
f")",
|
|
175
|
+
"",
|
|
176
|
+
"# Simplified API key middleware that validates presence",
|
|
171
177
|
"class ApiKeyMiddleware(BaseHTTPMiddleware):",
|
|
172
178
|
" async def dispatch(self, request: Request, call_next):",
|
|
179
|
+
" # Debug mode from environment",
|
|
180
|
+
" debug = os.environ.get('GOLF_API_KEY_DEBUG', '').lower() == 'true'",
|
|
181
|
+
" ",
|
|
173
182
|
" api_key_config = get_api_key_config()",
|
|
183
|
+
" ",
|
|
174
184
|
" if api_key_config:",
|
|
175
185
|
" # Extract API key from the configured header",
|
|
176
186
|
" header_name = api_key_config.header_name",
|
|
@@ -183,109 +193,39 @@ def generate_api_key_auth_components(server_name: str, opentelemetry_enabled: bo
|
|
|
183
193
|
" api_key = v",
|
|
184
194
|
" break",
|
|
185
195
|
" ",
|
|
186
|
-
" #
|
|
196
|
+
" # Process the API key if found",
|
|
197
|
+
" if api_key:",
|
|
198
|
+
" # Strip prefix if configured",
|
|
199
|
+
" if header_prefix and api_key.startswith(header_prefix):",
|
|
200
|
+
" api_key = api_key[len(header_prefix):]",
|
|
201
|
+
" ",
|
|
202
|
+
" # Store the API key in request state for tools to access",
|
|
203
|
+
" request.state.api_key = api_key",
|
|
204
|
+
" ",
|
|
205
|
+
" # Also store in context variable for tools",
|
|
206
|
+
" set_api_key(api_key)",
|
|
207
|
+
" ",
|
|
208
|
+
" # Check if API key is required but missing",
|
|
187
209
|
" if api_key_config.required and not api_key:",
|
|
188
210
|
" return JSONResponse(",
|
|
189
211
|
" {'error': 'unauthorized', 'detail': f'Missing required {header_name} header'},",
|
|
190
212
|
" status_code=401,",
|
|
191
213
|
" headers={'WWW-Authenticate': f'{header_name} realm=\"MCP Server\"'}",
|
|
192
214
|
" )",
|
|
193
|
-
" ",
|
|
194
|
-
" # Strip prefix if configured and present",
|
|
195
|
-
" if api_key and header_prefix and api_key.startswith(header_prefix):",
|
|
196
|
-
" api_key = api_key[len(header_prefix):]",
|
|
197
|
-
" elif api_key and header_prefix and api_key_config.required:",
|
|
198
|
-
" # Has API key but wrong format when required",
|
|
199
|
-
" return JSONResponse(",
|
|
200
|
-
" {'error': 'unauthorized', 'detail': f'Invalid {header_name} format, expected prefix: {header_prefix}'},",
|
|
201
|
-
" status_code=401,",
|
|
202
|
-
" headers={'WWW-Authenticate': f'{header_name} realm=\"MCP Server\"'}",
|
|
203
|
-
" )",
|
|
204
|
-
" ",
|
|
205
|
-
" # Store the API key in context for tools to access",
|
|
206
|
-
" set_api_key(api_key)",
|
|
207
215
|
" ",
|
|
208
216
|
" # Continue with the request",
|
|
209
|
-
"
|
|
210
|
-
" return response",
|
|
217
|
+
" return await call_next(request)",
|
|
211
218
|
"",
|
|
212
219
|
]
|
|
213
220
|
|
|
214
221
|
# API key auth is handled via middleware, not FastMCP constructor args
|
|
215
222
|
fastmcp_args = {}
|
|
216
223
|
|
|
217
|
-
# Code to run after FastMCP instance is created
|
|
218
|
-
# FastMCP doesn't expose .app directly, so we need to use custom_route
|
|
219
|
-
# to add a middleware-like functionality
|
|
220
|
-
post_init_code = [
|
|
221
|
-
"# API key authentication via custom middleware function",
|
|
222
|
-
"# Since FastMCP doesn't expose .app, we'll use a different approach",
|
|
223
|
-
"import functools",
|
|
224
|
-
"from starlette.responses import JSONResponse",
|
|
225
|
-
"",
|
|
226
|
-
"# Store original method references",
|
|
227
|
-
"_original_call_tool = mcp._mcp_call_tool if hasattr(mcp, '_mcp_call_tool') else None",
|
|
228
|
-
"_original_read_resource = mcp._mcp_read_resource if hasattr(mcp, '_mcp_read_resource') else None",
|
|
229
|
-
"_original_get_prompt = mcp._mcp_get_prompt if hasattr(mcp, '_mcp_get_prompt') else None",
|
|
230
|
-
"",
|
|
231
|
-
"# Wrapper to extract API key before processing",
|
|
232
|
-
"def with_api_key_extraction(original_method):",
|
|
233
|
-
" @functools.wraps(original_method)",
|
|
234
|
-
" async def wrapper(request, *args, **kwargs):",
|
|
235
|
-
" # Extract API key from request headers",
|
|
236
|
-
" api_key_config = get_api_key_config()",
|
|
237
|
-
" if api_key_config and hasattr(request, 'headers'):",
|
|
238
|
-
" header_name = api_key_config.header_name",
|
|
239
|
-
" header_prefix = api_key_config.header_prefix",
|
|
240
|
-
" ",
|
|
241
|
-
" # Case-insensitive header lookup",
|
|
242
|
-
" api_key = None",
|
|
243
|
-
" for k, v in request.headers.items():",
|
|
244
|
-
" if k.lower() == header_name.lower():",
|
|
245
|
-
" api_key = v",
|
|
246
|
-
" break",
|
|
247
|
-
" ",
|
|
248
|
-
" # Check if API key is required and missing",
|
|
249
|
-
" if api_key_config.required and not api_key:",
|
|
250
|
-
" return JSONResponse(",
|
|
251
|
-
" {'error': 'unauthorized', 'detail': f'Missing required {header_name} header'},",
|
|
252
|
-
" status_code=401,",
|
|
253
|
-
" headers={'WWW-Authenticate': f'{header_name} realm=\"MCP Server\"'}",
|
|
254
|
-
" )",
|
|
255
|
-
" ",
|
|
256
|
-
" # Strip prefix if configured and present",
|
|
257
|
-
" if api_key and header_prefix and api_key.startswith(header_prefix):",
|
|
258
|
-
" api_key = api_key[len(header_prefix):]",
|
|
259
|
-
" elif api_key and header_prefix and api_key_config.required:",
|
|
260
|
-
" # Has API key but wrong format when required",
|
|
261
|
-
" return JSONResponse(",
|
|
262
|
-
" {'error': 'unauthorized', 'detail': f'Invalid {header_name} format, expected prefix: {header_prefix}'},",
|
|
263
|
-
" status_code=401,",
|
|
264
|
-
" headers={'WWW-Authenticate': f'{header_name} realm=\"MCP Server\"'}",
|
|
265
|
-
" )",
|
|
266
|
-
" ",
|
|
267
|
-
" # Store the API key in context for tools to access",
|
|
268
|
-
" set_api_key(api_key)",
|
|
269
|
-
" ",
|
|
270
|
-
" # Call the original method",
|
|
271
|
-
" return await original_method(request, *args, **kwargs)",
|
|
272
|
-
" return wrapper",
|
|
273
|
-
"",
|
|
274
|
-
"# Wrap the MCP methods if they exist",
|
|
275
|
-
"if _original_call_tool:",
|
|
276
|
-
" mcp._mcp_call_tool = with_api_key_extraction(_original_call_tool)",
|
|
277
|
-
"if _original_read_resource:",
|
|
278
|
-
" mcp._mcp_read_resource = with_api_key_extraction(_original_read_resource)",
|
|
279
|
-
"if _original_get_prompt:",
|
|
280
|
-
" mcp._mcp_get_prompt = with_api_key_extraction(_original_get_prompt)",
|
|
281
|
-
]
|
|
282
|
-
|
|
283
224
|
return {
|
|
284
225
|
"imports": auth_imports,
|
|
285
226
|
"setup_code": setup_code_lines,
|
|
286
227
|
"fastmcp_args": fastmcp_args,
|
|
287
|
-
"has_auth": True
|
|
288
|
-
"post_init_code": post_init_code
|
|
228
|
+
"has_auth": True
|
|
289
229
|
}
|
|
290
230
|
|
|
291
231
|
|