golf-mcp 0.1.9__py3-none-any.whl → 0.1.10__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 CHANGED
@@ -1 +1 @@
1
- __version__ = "0.1.9"
1
+ __version__ = "0.1.10"
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
- return _current_api_key.get()
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/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
- imports.append("from fastmcp.server.http import create_sse_app")
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,35 @@ class CodeGenerator:
764
758
 
765
759
  # Transport-specific run methods
766
760
  if self.settings.transport == "sse":
767
- main_code.extend([
768
- " # For SSE, FastMCP's run method handles auth integration better",
769
- " mcp.run(transport=\"sse\", host=host, port=port, log_level=\"info\")"
770
- ])
771
- elif self.settings.transport == "streamable-http":
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
+ " # Run with the configured app",
769
+ " uvicorn.run(app, host=host, port=port, log_level=\"info\")"
770
+ ])
771
+ else:
772
+ main_code.extend([
773
+ " # For SSE, FastMCP's run method handles auth integration better",
774
+ " mcp.run(transport=\"sse\", host=host, port=port, log_level=\"info\")"
775
+ ])
776
+ elif self.settings.transport in ["streamable-http", "http"]:
772
777
  main_code.extend([
773
778
  " # Create HTTP app and run with uvicorn",
774
779
  " app = mcp.http_app()",
775
780
  ])
776
781
 
782
+ # Check if we need to add API key middleware
783
+ api_key_config = get_api_key_config()
784
+ if auth_components.get("has_auth") and api_key_config:
785
+ main_code.extend([
786
+ " # Add API key middleware",
787
+ " app.add_middleware(ApiKeyMiddleware)",
788
+ ])
789
+
777
790
  # Add OpenTelemetry middleware to the HTTP app if enabled
778
791
  if self.settings.opentelemetry_enabled:
779
792
  main_code.extend([
@@ -800,7 +813,6 @@ class CodeGenerator:
800
813
  env_section +
801
814
  auth_setup_code +
802
815
  server_code_lines +
803
- post_init_code +
804
816
  component_registrations +
805
817
  main_code
806
818
  )
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.helpers import set_api_key",
163
- "from golf.auth.api_key import get_api_key_config",
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
- "# Middleware to extract API key from headers",
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
- " # Check if API key is required and missing",
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
- " response = await call_next(request)",
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
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: golf-mcp
3
- Version: 0.1.9
3
+ Version: 0.1.10
4
4
  Summary: Framework for building MCP servers
5
5
  Author-email: Antoni Gmitruk <antoni@golf.dev>
6
6
  License-Expression: Apache-2.0
@@ -1,7 +1,7 @@
1
- golf/__init__.py,sha256=248SFgOW8tTzDpyY6euJ1BwIHMa4uimdKSyc2FGEEZE,21
2
- golf/auth/__init__.py,sha256=nh22WdganrEtp0YnxX1dmk6euuUFu8zh1BWxi1LGZnI,4107
1
+ golf/__init__.py,sha256=jLGuFdEwhMvHvklOJPvsqvbHQj9TW5k2grc-tedu-YE,22
2
+ golf/auth/__init__.py,sha256=JlpBJp357WFuM0E0j8k46c5EFzsduuquyHqr3aajTYo,4130
3
3
  golf/auth/api_key.py,sha256=TWJJ1tyVPSp1vN61opn3DdGKfQkTLX2w-YyLO4eeRPk,2495
4
- golf/auth/helpers.py,sha256=eKUIhdsaxa9bBtU6BaVZszTtS1ZV1v1fzvCkXV__9pM,2965
4
+ golf/auth/helpers.py,sha256=rmkBTkW3jL_j4aHttcm__E-8RDl_vS5Fg8-Vq79Dmwo,6683
5
5
  golf/auth/oauth.py,sha256=MGtuKMSt77yihuZiuiEm33xAlXJynIMcFmMLZRlppdg,31525
6
6
  golf/auth/provider.py,sha256=-iIjw1XruxgpWTrwYBX9dbf_sLPlx5vZxZsM0E4Dp64,3931
7
7
  golf/cli/__init__.py,sha256=MG53_GB5QcXHJAwSUKhy3xWLWwzc3FrnFbcCg4z6M0w,45
@@ -11,8 +11,8 @@ golf/commands/build.py,sha256=yhcUrK9gHnXNuLPZ2brcmtMgR8wXMBlEBcaBgTKkanI,2295
11
11
  golf/commands/init.py,sha256=I-fe7PBDX0vfKCLGXMppD7Uo03LzRbx-bCM2Mt3UzdU,7155
12
12
  golf/commands/run.py,sha256=dLrjmpypfvInDkA-KgEUyKrTvkvp59yea5tUyxk_Ej4,1989
13
13
  golf/core/__init__.py,sha256=RDSMAkB5NDaV7W5OFJ--miqv6JmvM3rI9ashndqM3X4,52
14
- golf/core/builder.py,sha256=5N2OwEtpPnjtSYxFzV8f_hBR6BUddD5p7zrPwaHmZjU,48256
15
- golf/core/builder_auth.py,sha256=ySu_nzoUgGYEP-8DCoSFwgoEW6NMFiQ_MP0v6akOEUI,17217
14
+ golf/core/builder.py,sha256=0yyAK-jdFf-35S1KhM2SiMm0Tk3ydfQn019iDNgem74,48960
15
+ golf/core/builder_auth.py,sha256=R7fZyGiigOPVaqR59l6m_5kJWNL86TbYs7p6qTgmwYs,13637
16
16
  golf/core/builder_telemetry.py,sha256=v2LnlHRWg9JqgplfZkV3zm1Jpo8QQBr7hlY8NLhlu8o,2694
17
17
  golf/core/config.py,sha256=gZ3eE8VIvDgIrLTizNq9XqkgfMkRg8Pm06gSVV51arA,6806
18
18
  golf/core/parser.py,sha256=sCVMWO7sGkSaKkU9LiHC3O9CTcrZxUbxnjdtwP7ne_o,19251
@@ -47,9 +47,9 @@ golf/examples/basic/tools/payments/common.py,sha256=z5shSOZizUEnxBmGUSYghxmNwIvu
47
47
  golf/examples/basic/tools/payments/refund.py,sha256=3auhKzuwPLgpoyUDz0p8lUWUY_fXNe0RYadQBxEvpB4,1603
48
48
  golf/telemetry/__init__.py,sha256=TFinunN7eFKEHMFUXjPBpz-JzuEu59QzrXwgg85YlQs,397
49
49
  golf/telemetry/instrumentation.py,sha256=520owHHBHlm819XD4FJ2dXrGbmGAjOMBXRREJJRgt7o,22890
50
- golf_mcp-0.1.9.dist-info/licenses/LICENSE,sha256=5_j2f6fTJmvfmUewzElhkpAaXg2grVoxKouOA8ihV6E,11348
51
- golf_mcp-0.1.9.dist-info/METADATA,sha256=hjiUAnMdRZaAj6yuGpvGu08cFNHPlomW3-XRdfWlRUg,10909
52
- golf_mcp-0.1.9.dist-info/WHEEL,sha256=zaaOINJESkSfm_4HQVc5ssNzHCPXhJm0kEUakpsEHaU,91
53
- golf_mcp-0.1.9.dist-info/entry_points.txt,sha256=5y7rHYM8jGpU-nfwdknCm5XsApLulqsnA37MO6BUTYg,43
54
- golf_mcp-0.1.9.dist-info/top_level.txt,sha256=BQToHcBUufdyhp9ONGMIvPE40jMEtmI20lYaKb4hxOg,5
55
- golf_mcp-0.1.9.dist-info/RECORD,,
50
+ golf_mcp-0.1.10.dist-info/licenses/LICENSE,sha256=5_j2f6fTJmvfmUewzElhkpAaXg2grVoxKouOA8ihV6E,11348
51
+ golf_mcp-0.1.10.dist-info/METADATA,sha256=l5TFVZ6-xyVSghkCe8raj0EuB5rikTnz4jvcg5fpkLo,10910
52
+ golf_mcp-0.1.10.dist-info/WHEEL,sha256=zaaOINJESkSfm_4HQVc5ssNzHCPXhJm0kEUakpsEHaU,91
53
+ golf_mcp-0.1.10.dist-info/entry_points.txt,sha256=5y7rHYM8jGpU-nfwdknCm5XsApLulqsnA37MO6BUTYg,43
54
+ golf_mcp-0.1.10.dist-info/top_level.txt,sha256=BQToHcBUufdyhp9ONGMIvPE40jMEtmI20lYaKb4hxOg,5
55
+ golf_mcp-0.1.10.dist-info/RECORD,,