### Golf.json Configuration File Example Source: https://context7.com/golf-mcp/golf/llms.txt The project configuration file supports all Settings fields and can be overridden by environment variables prefixed with GOLF_. ```json { "name": "My MCP Server", "description": "An example Golf server", "host": "localhost", "port": 3000, "transport": "streamable-http", "opentelemetry_enabled": true, "detailed_tracing": false, "stateless_http": false, "metrics_enabled": true, "metrics_path": "/metrics", "health_check_enabled": false, "tools_dir": "tools", "resources_dir": "resources", "prompts_dir": "prompts", "output_dir": "dist" } ``` -------------------------------- ### Test CLI Installation (Bash) Source: https://github.com/golf-mcp/golf/blob/main/CLAUDE.md Verify that the Golf CLI has been installed correctly by checking its version. This is a simple check after installation. ```bash golf --version ``` -------------------------------- ### Install in Development Mode (Bash) Source: https://github.com/golf-mcp/golf/blob/main/CLAUDE.md Install the project in development mode, including telemetry dependencies. This is typically used when setting up the project for local development. ```bash make install-dev ``` -------------------------------- ### Build and Run Golf Server Source: https://github.com/golf-mcp/golf/blob/main/src/golf/examples/basic/README.md Commands to build the server for development and then start the Golf server. Ensure you have completed the initialization and configuration steps. ```bash golf build dev golf run ``` -------------------------------- ### Initialize a new Golf project Source: https://context7.com/golf-mcp/golf/llms.txt Scaffolds a new Golf project directory with example files and configuration. Use --output-dir to specify a custom location. ```bash golf init my-agent golf init my-agent --output-dir /srv/projects ``` -------------------------------- ### Install Golf MCP Source: https://github.com/golf-mcp/golf/blob/main/README.md Install the Golf MCP framework using pip. Python 3.10+ is recommended. ```bash pip install golf-mcp ``` -------------------------------- ### Initialize Golf Project Source: https://github.com/golf-mcp/golf/blob/main/README.md Use the Golf CLI to scaffold a new project. This creates a directory with a basic project structure, example components, and a configuration file. ```bash golf init your-project-name ``` -------------------------------- ### Install Prometheus Metrics Dependency Source: https://context7.com/golf-mcp/golf/llms.txt Install the necessary package for Prometheus metrics support in Golf. Ensure the `prometheus-client` optional dependency is installed. ```bash pip install "golf-mcp[metrics]" ``` -------------------------------- ### Configure API Key Authentication Source: https://github.com/golf-mcp/golf/blob/main/src/golf/examples/basic/README.md Set up API key authentication for your Golf server. This example configures the header name, prefix, and whether the key is required. ```python # auth.py from golf.auth import configure_api_key configure_api_key( header_name="Authorization", header_prefix="Bearer ", required=True ) ``` -------------------------------- ### Define a Resource Source: https://github.com/golf-mcp/golf/blob/main/src/golf/examples/basic/README.md Example of defining a resource in Python. It requires a 'resource_uri' and an asynchronous export function that returns data. This allows LLMs to read data. ```python # resources/status.py resource_uri = "status://server" async def status() -> dict: """Get server status information.""" return {"status": "running", "timestamp": "2024-01-01T00:00:00Z"} export = status ``` -------------------------------- ### Define a Tool in Golf Source: https://github.com/golf-mcp/golf/blob/main/README.md Create a new tool by adding a Python file to the 'tools/' directory. The module docstring serves as the component's description. This example defines a simple 'hello' tool with input validation and a structured output. ```python # tools/hello.py """Hello World tool {{project_name}}.""" from typing import Annotated from pydantic import BaseModel, Field class Output(BaseModel): """Response from the hello tool.""" message: str async def hello( name: Annotated[str, Field(description="The name of the person to greet")] = "World", greeting: Annotated[str, Field(description="The greeting phrase to use")] = "Hello" ) -> Output: """Say hello to the given name. This is a simple example tool that demonstrates the basic structure of a tool implementation in Golf. """ print(f"{greeting} {name}...") return Output(message=f"{greeting}, {name}!") ``` -------------------------------- ### Define a Prompt Source: https://github.com/golf-mcp/golf/blob/main/src/golf/examples/basic/README.md Example of defining a system prompt in Python. The function should return a list of message dictionaries, typically used to configure the assistant's behavior. ```python # prompts/assistant.py async def assistant() -> list[dict]: """System prompt for a helpful assistant.""" return [ { "role": "system", "content": "You are a helpful assistant for {{project_name}}." } ] export = assistant ``` -------------------------------- ### Get Weather for City Resource Source: https://context7.com/golf-mcp/golf/llms.txt Defines a resource to fetch current weather data for a specific city using a URI template. ```APIDOC ## weather://city/{city} ### Description Provides current weather information for a specified city. ### Method GET (simulated) ### Endpoint weather://city/{city} ### Parameters #### Path Parameters * **city** (str) - Required - The name of the city for which to retrieve weather data. #### Query Parameters None #### Request Body None ### Request Example ```python # Example usage within Golf weather_data = await client.get("weather://city/London") ``` ### Response #### Success Response (200) - **city** (str) - The name of the city. - **temperature** (int) - The current temperature. - **conditions** (str) - A description of the current weather conditions. - **time** (str) - The timestamp when the weather data was recorded (ISO format). - **unit** (str) - The unit of temperature measurement (e.g., "fahrenheit"). #### Response Example ```json { "city": "London", "temperature": 72, "conditions": "Partly Cloudy", "time": "2023-10-27T10:30:00.123456", "unit": "fahrenheit" } ``` ``` -------------------------------- ### Define a Tool Function Source: https://github.com/golf-mcp/golf/blob/main/src/golf/examples/basic/README.md Example of defining an asynchronous tool function in Python. The function should be exported using 'export = function_name'. This allows LLMs to call it. ```python # tools/calculator.py async def add(a: int, b: int) -> int: """Add two numbers together.""" return a + b export = add ``` -------------------------------- ### Scrape Prometheus Metrics Source: https://context7.com/golf-mcp/golf/llms.txt After starting the Golf server, you can scrape the exposed Prometheus metrics endpoint using `curl`. The output will include metric types and values. ```bash # After starting the server, scrape metrics: curl http://localhost:3000/metrics # HELP python_gc_objects_collected_total ... # TYPE python_gc_objects_collected_total counter # ... ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/golf-mcp/golf/blob/main/src/golf/examples/basic/README.md Change the current directory to your newly initialized project. This is the first step after bootstrapping a new project. ```bash cd your-project-name ``` -------------------------------- ### Define a Welcome Prompt Source: https://context7.com/golf-mcp/golf/llms.txt Place an async Python file in the `prompts/` directory. The function should return a list of role/content dictionaries in the MCP messages format. ```python async def welcome() -> list[dict]: """Provide a welcome prompt for new users. Returns a list of MCP-formatted message dicts with 'role' and 'content' keys. """ return [ { "role": "system", "content": ( "You are an assistant for this application. " "Help users understand the system and its capabilities." ), }, { "role": "user", "content": "Welcome! How can I get started?", }, ] export = welcome # Registered as MCP prompt "welcome" ``` -------------------------------- ### Run Golf Development Server Source: https://github.com/golf-mcp/golf/blob/main/README.md Navigate to your project directory and build/run the development server. The server typically runs on http://localhost:3000. ```bash cd your-project-name golf build dev golf run ``` -------------------------------- ### Configure Development Authentication Tokens Source: https://github.com/golf-mcp/golf/blob/main/src/golf/examples/basic/README.md Set up development authentication with predefined tokens. Each token can have associated client IDs and scopes for testing purposes. ```python # auth.py from golf.auth import configure_dev_auth configure_dev_auth( tokens={ "dev-token-123": { "client_id": "dev-client", "scopes": ["read", "write"] } } ) ``` -------------------------------- ### Build Golf project for development or production Source: https://context7.com/golf-mcp/golf/llms.txt Compiles project components into a FastMCP application in the dist/ directory. 'dev' includes environment variables, 'prod' excludes them. Use --output-dir to specify a custom output directory. ```bash golf build dev golf build prod golf build dev --output-dir ./out ``` -------------------------------- ### Welcome Prompt Source: https://context7.com/golf-mcp/golf/llms.txt Defines a welcome prompt for new users, formatted as a list of messages for an AI assistant. ```APIDOC ## welcome() ### Description Generates a standard welcome message and system prompt for new users interacting with the application's AI assistant. ### Parameters None ### Request Example ```python # Example usage within Golf welcome_messages = await client.call("welcome") ``` ### Response #### Success Response (200) - **(list of dicts)** - A list where each dictionary contains 'role' (e.g., 'system', 'user') and 'content' (the message text). #### Response Example ```json [ { "role": "system", "content": "You are an assistant for this application. Help users understand the system and its capabilities." }, { "role": "user", "content": "Welcome! How can I get started?" } ] ``` ``` -------------------------------- ### Enable OpenTelemetry Tracing Source: https://github.com/golf-mcp/golf/blob/main/README.md Enable OpenTelemetry tracing by setting environment variables for the exporter and endpoint. Run the 'golf run' command to activate telemetry. ```bash export OTEL_TRACES_EXPORTER="otlp_http" export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318/v1/traces" golf run # ✅ Telemetry enabled ``` -------------------------------- ### Define a Weather Resource with URI Parameters Source: https://context7.com/golf-mcp/golf/llms.txt Define a resource by placing an async Python file in the `resources/` directory. The `resource_uri` template maps parameters to function arguments. ```python from datetime import datetime from typing import Any resource_uri = "weather://city/{city}" async def get_weather_for_city(city: str) -> dict[str, Any]: """Provide current weather for a specific city. URI template parameters ({city}) are automatically mapped to function arguments. Access via MCP as: weather://city/London """ # Simulate fetching weather data return { "city": city, "temperature": 72, "conditions": "Partly Cloudy", "time": datetime.now().isoformat(), "unit": "fahrenheit", } export = get_weather_for_city # Registered as resource template "weather://city/{city}" ``` -------------------------------- ### Designate Entry Point Function Source: https://github.com/golf-mcp/golf/blob/main/README.md Export the main function to be discovered by Golf. The module docstring serves as the tool's description, and parameters are inferred from the function signature. ```python export = hello ``` -------------------------------- ### Run the compiled FastMCP server Source: https://context7.com/golf-mcp/golf/llms.txt Runs the FastMCP server from the dist/ directory, with options to auto-build if needed, override host/port, and specify a custom dist directory. ```bash golf run golf run --host 0.0.0.0 --port 8080 golf run --dist-dir ./out --no-build ``` -------------------------------- ### Configure Development Authentication Source: https://github.com/golf-mcp/golf/blob/main/CLAUDE.md Set up development authentication by providing a dictionary of tokens and their associated client IDs and scopes. Specify required scopes for all authenticated requests. ```python from golf.auth import configure_dev_auth configure_dev_auth( tokens={ "dev-token-123": { "client_id": "dev-client", "scopes": ["read", "write"], } }, required_scopes=["read"], ) ``` -------------------------------- ### Load Golf project settings and find project root Source: https://context7.com/golf-mcp/golf/llms.txt Use `find_project_root` to locate the project's root directory and `load_settings` to programmatically access project configuration from Python. This is useful for build scripts or custom tooling. ```python from pathlib import Path from golf.core.config import load_settings, find_project_root, find_config_path # Locate project root by walking up from the current directory project_root, config_path = find_project_root() if project_root: print(f"Project root: {project_root}") # e.g., /srv/my-agent print(f"Config file: {config_path}") # e.g., /srv/my-agent/golf.json settings = load_settings(project_root) print(settings.name) # "My MCP Server" print(settings.host) # "localhost" print(settings.port) # 3000 print(settings.transport) # "streamable-http" print(settings.opentelemetry_enabled) # False print(settings.metrics_enabled) # False else: print("Not inside a Golf project") # Load from an explicit path: settings = load_settings(Path("/srv/my-agent")) ``` -------------------------------- ### Basic Golf Server Configuration Source: https://github.com/golf-mcp/golf/blob/main/README.md Configure basic Golf server settings including name, host, port, transport, and OpenTelemetry options. Choose transport from 'sse', 'streamable-http', or 'stdio'. ```json { "name": "My Golf Server", "host": "localhost", "port": 3000, "transport": "sse", "opentelemetry_enabled": false, "detailed_tracing": false } ``` -------------------------------- ### Run All Tests with Coverage (Bash) Source: https://github.com/golf-mcp/golf/blob/main/CLAUDE.md Execute all tests in the project and generate a coverage report. This command is useful for ensuring code quality and identifying untested areas. ```bash make test # OR directly: python -m pytest tests/ -v --cov=golf --cov-report=term-missing --cov-report=html ``` -------------------------------- ### Configure Static Token Authentication Source: https://github.com/golf-mcp/golf/blob/main/README.md Configure static tokens for development environments. Define tokens with associated client IDs and scopes. ```python from golf.auth import configure_auth, StaticTokenConfig configure_auth(StaticTokenConfig( tokens={"dev-token": {"client_id": "dev", "scopes": ["read"]}} )) ``` -------------------------------- ### Define a Tool in Golf Source: https://context7.com/golf-mcp/golf/llms.txt Place an async Python file in the tools/ directory. The function's docstring serves as the MCP tool description. Use Annotated[type, Field(...)] for parameter schema metadata and export = function_name to designate the entry point. ```python from typing import Annotated from pydantic import Field async def charge(amount: Annotated[int, Field(gt=0)]): """Charges the user's account for the given amount.""" # ... implementation ... return f"Charged ${amount}" export = charge ``` -------------------------------- ### Enable OpenTelemetry tracing via environment variables Source: https://context7.com/golf-mcp/golf/llms.txt Configure automatic OpenTelemetry tracing for Golf projects by setting environment variables like `GOLF_OPENTELEMETRY_ENABLED` and `GOLF_DETAILED_TRACING`. These settings override configurations in `golf.json`. ```bash # Enable via environment variables (overrides golf.json) export GOLF_OPENTELEMETRY_ENABLED=true export GOLF_DETAILED_TRACING=false # Set true to capture inputs/outputs (may expose PII) ``` -------------------------------- ### Run Linting with Ruff (Bash) Source: https://github.com/golf-mcp/golf/blob/main/CLAUDE.md Check the code quality of the src/ directory using Ruff's linting capabilities. This helps maintain code consistency and identify potential issues. ```bash python -m ruff check src/ ``` -------------------------------- ### Configure OpenTelemetry Tracing Source: https://context7.com/golf-mcp/golf/llms.txt Set environment variables to enable OTLP HTTP tracing and specify the collector endpoint and service name. This is used for sending traces to a local Jaeger or OTLP collector. ```bash export OTEL_TRACES_EXPORTER=otlp_http export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318/v1/traces export OTEL_SERVICE_NAME=my-golf-server ``` -------------------------------- ### Create a record with user-confirmed details Source: https://context7.com/golf-mcp/golf/llms.txt Use `elicit` for structured and multiple-choice input, and `elicit_confirmation` to confirm user actions before proceeding. This is useful for interactive user input in command-line tools or agents. ```python from pydantic import BaseModel from golf.utilities import elicit, elicit_confirmation class RecordDetails(BaseModel): title: str category: str priority: int class RecordResult(BaseModel): record_id: str message: str async def create_record() -> RecordResult: """Create a new record after collecting details from the user.""" # Structured elicitation — returns a validated RecordDetails instance details = await elicit( "Please provide the record details:", RecordDetails, ) # Multiple-choice elicitation — returns a string visibility = await elicit( "Who should see this record?", ["private", "team", "public"], ) # Confirmation elicitation — returns True/False confirmed = await elicit_confirmation( f"Create '{details.title}' ({visibility}) with priority {details.priority}?" ) if not confirmed: return RecordResult(record_id="", message="Creation cancelled by user") # ... persist record ... return RecordResult( record_id="rec_abc123", message=f"Created '{details.title}' as {visibility}", ) export = create_record ``` -------------------------------- ### Summarize Text with LLM Source: https://context7.com/golf-mcp/golf/llms.txt Summarize provided text using a connected LLM. Allows specifying maximum words and model preferences. Requires the `golf.utilities.sample` function. ```python # tools/summarize.py """Summarize text using the connected LLM.""" from typing import Annotated from pydantic import BaseModel, Field from golf.utilities import sample class SummaryResult(BaseModel): summary: str word_count: int async def summarize( text: Annotated[str, Field(description="The text to summarize")], max_words: Annotated[int, Field(description="Maximum words in summary")] = 100, ) -> SummaryResult: """Summarize the provided text using the connected LLM.""" summary = await sample( f"Summarize the following text in at most {max_words} words:\n\n{text}", system_prompt="You are a precise summarization assistant. Be concise.", temperature=0.3, max_tokens=300, model_preferences=["claude-3-haiku", "gpt-4o-mini"], ) return SummaryResult(summary=summary, word_count=len(summary.split())) export = summarize ``` -------------------------------- ### Format Code with Ruff (Bash) Source: https://github.com/golf-mcp/golf/blob/main/CLAUDE.md Format the code in the src/ and tests/ directories using Ruff's formatting capabilities. This ensures consistent code style across the project. ```bash python -m ruff format src/ tests/ ``` -------------------------------- ### Parse project components using Golf AST parser Source: https://context7.com/golf-mcp/golf/llms.txt Employ `parse_project` to analyze a Golf project directory and generate a structured map of its tools, resources, and prompts. This is valuable for project introspection and custom build processes. It raises a `ValueError` on ID collisions. ```python from pathlib import Path from golf.core.parser import parse_project, ComponentType project_path = Path("/srv/my-agent") components = parse_project(project_path) for tool in components[ComponentType.TOOL]: print(f"Tool: {tool.name}") print(f" File: {tool.module_path}") print(f" Docstring: {tool.docstring[:60]}...") print(f" Parameters: {tool.parameters}") print(f" Entry fn: {tool.entry_function}") for resource in components[ComponentType.RESOURCE]: print(f"Resource: {resource.name}") print(f" URI template: {resource.uri_template}") # Raises ValueError on ID collisions (two components with the same derived name) # Example tool output: # Tool: calculator # File: tools/calculator.py # Docstring: Evaluate a mathematical expression with optional LLM... # Parameters: ['expression', 'explain'] # Entry fn: calculate ``` -------------------------------- ### Configure Remote Authentication Integration Source: https://context7.com/golf-mcp/golf/llms.txt Integrates with a remote authorization server for resource server advertisement. The Golf server verifies tokens locally while advertising the upstream auth server. Configuration can be done via direct values or environment variables. The `token_verifier_config` specifies how local token verification is performed. ```python # auth.py from golf.auth import configure_auth, RemoteAuthConfig, JWTAuthConfig configure_auth( RemoteAuthConfig( authorization_servers=["https://auth.example.com"], resource_server_url="https://mcp.example.com", scopes_supported=["read", "write"], token_verifier_config=JWTAuthConfig( jwks_uri_env_var="JWKS_URI", issuer="https://auth.example.com", audience="https://mcp.example.com", ), ) ) ``` ```python # Via environment variables: configure_auth( RemoteAuthConfig( authorization_servers_env_var="AUTH_SERVERS", # comma-separated URLs resource_server_url_env_var="RESOURCE_URL", token_verifier_config=JWTAuthConfig(jwks_uri_env_var="JWKS_URI"), ) ) ``` -------------------------------- ### Enable Golf Telemetry Source: https://github.com/golf-mcp/golf/blob/main/README.md Re-enable telemetry collection using the 'golf telemetry enable' command. ```bash golf telemetry enable ``` -------------------------------- ### Define a Calculator Tool with Optional LLM Explanations Source: https://context7.com/golf-mcp/golf/llms.txt This tool evaluates mathematical expressions and can optionally provide LLM-powered explanations. Ensure valid characters are used in the expression. ```python from typing import Annotated from pydantic import BaseModel, Field from golf.utilities import sample class CalculationResult(BaseModel): """Result of a mathematical calculation.""" result: float operation: str expression: str async def calculate( expression: Annotated[ str, Field( description="Mathematical expression to evaluate (e.g., '2 + 3', '10 * 5')", examples=["2 + 3", "10 * 5.5", "(8 - 3) * 2"], ), ], explain: Annotated[ bool, Field(description="Whether to provide an LLM-powered step-by-step explanation") ] = False, ) -> CalculationResult: """Evaluate a mathematical expression with optional LLM explanation.""" allowed_chars = set("0123456789+-*/.() ") if not all(c in allowed_chars for c in expression): raise ValueError("Expression contains invalid characters") result = eval(expression, {"__builtins__": {}}, {}) if explain: explanation = await sample( f"Explain step by step: {expression} = {result}", system_prompt="You are a helpful math tutor.", max_tokens=200, ) expression = f"{expression}\n\nExplanation: {explanation}" return CalculationResult(result=float(result), operation="evaluate", expression=expression) export = calculate ``` -------------------------------- ### Configure Static Token Authentication for Development Source: https://context7.com/golf-mcp/golf/llms.txt Sets up static bearer token authentication, mapping tokens to client IDs and scopes. This is suitable for development and testing environments only and should not be used in production. The `required_scopes` apply to all requests. ```python # auth.py from golf.auth import configure_auth, StaticTokenConfig configure_auth( StaticTokenConfig( tokens={ "dev-token-123": { "client_id": "dev-client", "scopes": ["read", "write"], }, "admin-token-456": { "client_id": "admin-client", "scopes": ["read", "write", "admin"], }, }, required_scopes=["read"], # All requests must have "read" scope ) ) ``` ```python # Convenience shorthand (uses the tokens above as defaults): from golf.auth import configure_dev_auth configure_dev_auth(required_scopes=["read"]) ``` -------------------------------- ### Enable OpenTelemetry Tracing in golf.json Source: https://context7.com/golf-mcp/golf/llms.txt Configure OpenTelemetry tracing by setting `opentelemetry_enabled` to true in the `golf.json` file. `detailed_tracing` can be set to false to disable detailed tracing. ```json // golf.json — equivalent configuration { "name": "My Server", "opentelemetry_enabled": true, "detailed_tracing": false } ``` -------------------------------- ### Configure OAuth 2.0 Authorization Server Source: https://context7.com/golf-mcp/golf/llms.txt Configures the Golf server to act as a full OAuth 2.0 authorization server. It handles client registration, authorization flows, and token issuance. For production, HTTPS is mandatory for `base_url`, and using environment variables for configuration is recommended. Be cautious with dangerous scopes. ```python # auth.py from golf.auth import configure_auth, OAuthServerConfig configure_auth( OAuthServerConfig( base_url="https://mcp.example.com", # Must be HTTPS in production valid_scopes=["read", "write", "tools:run"], default_scopes=["read"], required_scopes=["read"], allow_token_revocation=True, ) ) ``` ```python # Using environment variables (recommended for production): configure_auth( OAuthServerConfig( base_url_env_var="OAUTH_BASE_URL", valid_scopes=["read", "write"], default_scopes=["read"], required_scopes=["read"], ) ) ``` -------------------------------- ### Configure API Key Extraction Source: https://context7.com/golf-mcp/golf/llms.txt Sets up API key extraction from request headers. The `header_prefix` is stripped before returning the raw key. Setting `required=True` ensures that requests without a valid API key will be rejected. ```python # auth.py — configure the header to read from from golf.auth.api_key import configure_api_key configure_api_key( header_name="Authorization", header_prefix="Bearer ", # Prefix stripped before returning the raw key required=True, ) ``` -------------------------------- ### configure_auth with StaticTokenConfig Source: https://context7.com/golf-mcp/golf/llms.txt Configures static bearer-token authentication for development and testing purposes. Not recommended for production. ```APIDOC ## configure_auth / StaticTokenConfig Configures static bearer-token authentication for development and testing. **Never use in production.** ```python # auth.py from golf.auth import configure_auth, StaticTokenConfig configure_auth( StaticTokenConfig( tokens={ "dev-token-123": { "client_id": "dev-client", "scopes": ["read", "write"], }, "admin-token-456": { "client_id": "admin-client", "scopes": ["read", "write", "admin"], }, }, required_scopes=["read"], # All requests must have "read" scope ) ) # Convenience shorthand (uses the tokens above as defaults): from golf.auth import configure_dev_auth configure_dev_auth(required_scopes=["read"]) ``` ``` -------------------------------- ### configure_auth with JWTAuthConfig Source: https://context7.com/golf-mcp/golf/llms.txt Configures JWT-based authentication using environment variables for the public key. ```APIDOC ## configure_auth / JWTAuthConfig Configures JWT authentication using a public key from an environment variable. ```python # auth.py from golf.auth import configure_auth, JWTAuthConfig configure_auth( JWTAuthConfig( public_key_env_var="JWT_PUBLIC_KEY", issuer="https://auth.internal.example.com", audience="my-mcp-server", required_scopes=["mcp:access"], ) ) # Missing issuer/audience in production triggers a UserWarning ``` ``` -------------------------------- ### Configure OAuth Proxy for Upstream Providers Source: https://context7.com/golf-mcp/golf/llms.txt Configures the Golf server to act as an OAuth proxy, bridging MCP clients with upstream OAuth providers using fixed client credentials. Configuration can use direct values or environment variables. The `token_verifier_config` is essential for verifying tokens from the upstream provider. Custom validation logic can be provided for redirect URIs. ```python # auth.py from golf.auth import configure_oauth_proxy, JWTAuthConfig jwt_config = JWTAuthConfig(jwks_uri_env_var="GITHUB_JWKS_URI") # Direct values: configure_oauth_proxy( authorization_endpoint="https://github.com/login/oauth/authorize", token_endpoint="https://github.com/login/oauth/access_token", client_id="my-github-app-id", client_secret="my-github-app-secret", base_url="https://mcp.example.com", token_verifier_config=jwt_config, scopes_supported=["read:user", "repo"], redirect_path="/oauth/callback", ) ``` ```python # Via environment variables (recommended): configure_oauth_proxy( authorization_endpoint_env_var="OAUTH_AUTH_ENDPOINT", token_endpoint_env_var="OAUTH_TOKEN_ENDPOINT", client_id_env_var="OAUTH_CLIENT_ID", client_secret_env_var="OAUTH_CLIENT_SECRET", base_url_env_var="OAUTH_BASE_URL", token_verifier_config=jwt_config, # Dynamic redirect URI validation using a callable: allowed_redirect_patterns_func=lambda: ["https://app.example.com/*"], redirect_uri_validator=lambda uri: uri.startswith("https://"), ) ``` -------------------------------- ### Call Upstream Service with API Key Source: https://context7.com/golf-mcp/golf/llms.txt Forward the user's API key to an upstream service. Ensure an API key is available before making the call. ```python from golf.auth import get_api_key import httpx async def call_upstream() -> dict: """Forward user's API key to an upstream service.""" api_key = get_api_key() if not api_key: return {"error": "No API key provided"} async with httpx.AsyncClient() as client: response = await client.get( "https://api.upstream.example.com/data", headers={"Authorization": f"Bearer {api_key}"}, ) response.raise_for_status() return response.json() export = call_upstream ``` -------------------------------- ### Configure API Key Authentication Source: https://github.com/golf-mcp/golf/blob/main/CLAUDE.md Configure API key authentication by specifying the header name and prefix. Set 'required' to True if authentication is mandatory for all requests. ```python from golf.auth import configure_api_key configure_api_key( header_name="Authorization", header_prefix="Bearer ", required=True, ) ``` -------------------------------- ### configure_auth with OAuthServerConfig Source: https://context7.com/golf-mcp/golf/llms.txt Configures the Golf server to act as an OAuth 2.0 authorization server, handling client registration and token issuance. ```APIDOC ## configure_auth / OAuthServerConfig Turns the Golf server itself into a full OAuth 2.0 authorization server, handling client registration, authorization flows, and token issuance. ```python # auth.py from golf.auth import configure_auth, OAuthServerConfig configure_auth( OAuthServerConfig( base_url="https://mcp.example.com", # Must be HTTPS in production valid_scopes=["read", "write", "tools:run"], default_scopes=["read"], required_scopes=["read"], allow_token_revocation=True, ) ) # Using environment variables (recommended for production): configure_auth( OAuthServerConfig( base_url_env_var="OAUTH_BASE_URL", valid_scopes=["read", "write"], default_scopes=["read"], required_scopes=["read"], ) ) # Scopes validated against RFC 6749 format; dangerous scopes ("admin", "*") trigger UserWarning ``` ``` -------------------------------- ### Configure JWT Authentication (Python) Source: https://github.com/golf-mcp/golf/blob/main/CLAUDE.md Configure JWT authentication for the Golf framework using FastMCP's built-in providers. This snippet should be placed in your auth.py file and requires environment variables for JWKS URI, issuer, and audience. ```python # In auth.py from golf.auth import configure_jwt_auth configure_jwt_auth( jwks_uri_env_var="JWKS_URI", # JWKS endpoint issuer_env_var="JWT_ISSUER", audience_env_var="JWT_AUDIENCE", required_scopes=["read:user"], ) ``` -------------------------------- ### Configure JWT Authentication Source: https://github.com/golf-mcp/golf/blob/main/README.md Configure JWT authentication for production environments. Ensure JWKS_URI, JWT_ISSUER, and JWT_AUDIENCE environment variables are set. Required scopes can also be specified. ```python from golf.auth import configure_auth, JWTAuthConfig configure_auth(JWTAuthConfig( jwks_uri_env_var="JWKS_URI", issuer_env_var="JWT_ISSUER", audience_env_var="JWT_AUDIENCE", required_scopes=["read", "write"] )) ``` -------------------------------- ### Configure JWT Authentication with Static Public Key Source: https://context7.com/golf-mcp/golf/llms.txt Configures JWT authentication using a static public key loaded from an environment variable. Ensure the JWT_PUBLIC_KEY environment variable is set. Issuer and audience validation are important for production security. ```python configure_auth( JWTAuthConfig( public_key_env_var="JWT_PUBLIC_KEY", issuer="https://auth.internal.example.com", audience="my-mcp-server", required_scopes=["mcp:access"], ) ) ``` -------------------------------- ### configure_auth with RemoteAuthConfig Source: https://context7.com/golf-mcp/golf/llms.txt Integrates with a remote authorization server for resource server advertisement, while verifying tokens locally. ```APIDOC ## configure_auth / RemoteAuthConfig Integrates with a remote authorization server for RFC 9728-compliant resource server advertisement. The Golf server verifies tokens locally (via JWT or static tokens) while advertising the upstream auth server. ```python # auth.py from golf.auth import configure_auth, RemoteAuthConfig, JWTAuthConfig configure_auth( RemoteAuthConfig( authorization_servers=["https://auth.example.com"], resource_server_url="https://mcp.example.com", scopes_supported=["read", "write"], token_verifier_config=JWTAuthConfig( jwks_uri_env_var="JWKS_URI", issuer="https://auth.example.com", audience="https://mcp.example.com", ), ) ) # Via environment variables: configure_auth( RemoteAuthConfig( authorization_servers_env_var="AUTH_SERVERS", # comma-separated URLs resource_server_url_env_var="RESOURCE_URL", token_verifier_config=JWTAuthConfig(jwks_uri_env_var="JWKS_URI"), ) ) ``` ``` -------------------------------- ### Configure OAuth Server Mode Source: https://github.com/golf-mcp/golf/blob/main/README.md Configure Golf to act as an OAuth 2.0 server. Specify the base URL of your Golf server and the valid scopes. ```python from golf.auth import configure_auth, OAuthServerConfig configure_auth(OAuthServerConfig( base_url="https://your-golf-server.com", valid_scopes=["read", "write", "admin"] )) ``` -------------------------------- ### configure_oauth_proxy Source: https://context7.com/golf-mcp/golf/llms.txt Configures the Golf server as an OAuth proxy to bridge MCP clients with upstream OAuth providers using fixed client credentials. ```APIDOC ## configure_oauth_proxy Configures the Golf server as an OAuth proxy — it bridges MCP clients (which use Dynamic Client Registration) with upstream OAuth providers that use fixed client credentials (GitHub Apps, Google Cloud, Okta). ```python # auth.py from golf.auth import configure_oauth_proxy, JWTAuthConfig jwt_config = JWTAuthConfig(jwks_uri_env_var="GITHUB_JWKS_URI") # Direct values: configure_oauth_proxy( authorization_endpoint="https://github.com/login/oauth/authorize", token_endpoint="https://github.com/login/oauth/access_token", client_id="my-github-app-id", client_secret="my-github-app-secret", base_url="https://mcp.example.com", token_verifier_config=jwt_config, scopes_supported=["read:user", "repo"], redirect_path="/oauth/callback", ) # Via environment variables (recommended): configure_oauth_proxy( authorization_endpoint_env_var="OAUTH_AUTH_ENDPOINT", token_endpoint_env_var="OAUTH_TOKEN_ENDPOINT", client_id_env_var="OAUTH_CLIENT_ID", client_secret_env_var="OAUTH_CLIENT_SECRET", base_url_env_var="OAUTH_BASE_URL", token_verifier_config=jwt_config, # Dynamic redirect URI validation using a callable: allowed_redirect_patterns_func=lambda: ["https://app.example.com/*"], redirect_uri_validator=lambda uri: uri.startswith("https://"), ) ``` ``` -------------------------------- ### Enable Prometheus Metrics in golf.json Source: https://context7.com/golf-mcp/golf/llms.txt Enable the Prometheus metrics endpoint by setting `metrics_enabled` to true and optionally specifying the `metrics_path` in `golf.json`. ```json // golf.json { "name": "My Server", "metrics_enabled": true, "metrics_path": "/metrics" } ``` -------------------------------- ### Configure JWT Authentication Source: https://github.com/golf-mcp/golf/blob/main/src/golf/examples/basic/README.md Configure JSON Web Token (JWT) authentication. This requires specifying the JWKS URI, issuer, and audience for token validation. ```python # auth.py from golf.auth import configure_jwt_auth configure_jwt_auth( jwks_uri="https://your-domain.auth0.com/.well-known/jwks.json", issuer="https://your-domain.auth0.com/", audience="https://your-api.example.com" ) ``` -------------------------------- ### summarize Source: https://context7.com/golf-mcp/golf/llms.txt Requests an LLM completion to summarize provided text. ```APIDOC ## summarize ### Description Summarize the provided text using the connected LLM. ### Parameters #### Arguments - **text** (string) - Required - The text to summarize. - **max_words** (integer) - Optional - Maximum words in the summary. Defaults to 100. ### Response #### Success Response - **SummaryResult** (object) - An object containing the summary and word count. - **summary** (string) - The generated summary. - **word_count** (integer) - The number of words in the generated summary. ``` -------------------------------- ### Extract Entities with Structured LLM Output Source: https://context7.com/golf-mcp/golf/llms.txt Extract named entities (persons, organizations, locations) from text and return them as a JSON object. Uses `golf.utilities.sample_structured` and requires specific format instructions for the LLM. ```python # tools/extract_entities.py """Extract named entities from text.""" from typing import Annotated from pydantic import BaseModel, Field from golf.utilities import sample_structured class EntityResult(BaseModel): raw_json: str async def extract_entities( text: Annotated[str, Field(description="Text to extract entities from")], ) -> EntityResult: """Extract named entities (persons, organizations, locations) as JSON.""" result = await sample_structured( f"Extract all named entities from:\n\n{text}", format_instructions=( 'Return a JSON object with keys "persons", "organizations", "locations", ' "each containing a list of strings." ), system_prompt="You are an expert at named entity recognition.", temperature=0.1, max_tokens=500, ) # result is a raw JSON string from the LLM return EntityResult(raw_json=result) export = extract_entities ``` -------------------------------- ### Configure JWT Bearer-Token Authentication Source: https://context7.com/golf-mcp/golf/llms.txt Configure JWT bearer-token authentication for the Golf server by calling `configure_auth` with `JWTAuthConfig`. Key material is read from environment variables at runtime. ```python from golf.auth import configure_auth, JWTAuthConfig # Production: JWKS endpoint (e.g., Auth0, Okta) configure_auth( JWTAuthConfig( jwks_uri_env_var="JWKS_URI", # e.g., https://tenant.auth0.com/.well-known/jwks.json issuer_env_var="JWT_ISSUER", # e.g., https://tenant.auth0.com/ audience_env_var="JWT_AUDIENCE", # e.g., https://my-api.example.com required_scopes=["read:data", "write:data"], algorithm="RS256", ) ) ``` -------------------------------- ### Calculator Tool Source: https://context7.com/golf-mcp/golf/llms.txt Defines an enhanced calculator tool that can evaluate mathematical expressions and optionally provide LLM-powered explanations. ```APIDOC ## calculate(expression: str, explain: bool = False) ### Description Evaluates a mathematical expression. If `explain` is True, it also generates an LLM-powered step-by-step explanation. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **expression** (str) - Required - Mathematical expression to evaluate (e.g., '2 + 3', '10 * 5'). * **explain** (bool) - Optional - Whether to provide an LLM-powered step-by-step explanation. Defaults to False. ### Request Example ```python # Example usage within Golf result = await client.call("calculator", expression="(10 + 5) * 2", explain=True) ``` ### Response #### Success Response (200) - **result** (float) - The numerical result of the calculation. - **operation** (str) - The type of operation performed (e.g., "evaluate"). - **expression** (str) - The original expression, potentially augmented with an explanation if `explain` was True. #### Response Example ```json { "result": 30.0, "operation": "evaluate", "expression": "(10 + 5) * 2\n\nExplanation: First, calculate the value inside the parentheses: 10 + 5 = 15. Then, multiply the result by 2: 15 * 2 = 30." } ``` ``` -------------------------------- ### configure_api_key Source: https://context7.com/golf-mcp/golf/llms.txt Configures API key extraction from request headers and provides a helper to retrieve the key within tool functions. ```APIDOC ## configure_api_key / get_api_key Configures API key extraction from request headers and provides a helper to retrieve the key inside any tool function. ```python # auth.py — configure the header to read from from golf.auth.api_key import configure_api_key configure_api_key( header_name="Authorization", header_prefix="Bearer ", # Prefix stripped before returning the raw key required=True, ) ``` ``` -------------------------------- ### Run Tests Without Coverage (Bash) Source: https://github.com/golf-mcp/golf/blob/main/CLAUDE.md Execute all tests in the project without generating a coverage report for faster execution. This is useful for quick checks during development. ```bash make test-fast # OR directly: python -m pytest tests/ -v ``` -------------------------------- ### Access FastMCP context for logging and progress Source: https://context7.com/golf-mcp/golf/llms.txt Retrieve the current FastMCP `Context` object using `get_current_context` to access logging (`ctx.info`) and progress reporting (`ctx.report_progress`) APIs within long-running tasks. ```python # tools/long_running_task.py """Demonstrate direct FastMCP context access.""" from pydantic import BaseModel from golf.utilities import get_current_context class TaskResult(BaseModel): steps_completed: int output: str async def run_task(steps: int = 5) -> TaskResult: """Run a multi-step task with progress logging.""" ctx = get_current_context() results = [] for i in range(1, steps + 1): await ctx.info(f"Step {i}/{steps} starting...") # ... do work ... results.append(f"step_{i}_done") await ctx.report_progress(i, steps) await ctx.info("All steps completed.") return TaskResult(steps_completed=steps, output=", ".join(results)) export = run_task ``` -------------------------------- ### Stripe Charge Tool Source: https://context7.com/golf-mcp/golf/llms.txt Defines a tool for charging a customer via Stripe, allowing for custom naming via the `@tool` decorator. ```APIDOC ## stripe_charge(amount: int, currency: str = "usd") ### Description Charges a customer via Stripe with a specified amount and currency. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **amount** (int) - Required - The amount to charge. * **currency** (str) - Optional - The currency for the charge. Defaults to "usd". ### Request Example ```python # Example usage within Golf charge_details = await client.call("stripe_charge", amount=100, currency="usd") ``` ### Response #### Success Response (200) - **charge_id** (str) - The unique identifier for the Stripe charge. - **amount** (int) - The charged amount. - **status** (str) - The status of the charge (e.g., "succeeded"). #### Response Example ```json { "charge_id": "ch_abc123", "amount": 100, "status": "succeeded" } ``` ``` -------------------------------- ### Proxy Request with Auth Token Source: https://context7.com/golf-mcp/golf/llms.txt Forward the caller's authorization token to an upstream API. This is useful for proxying requests that require authentication. ```python # tools/proxy_call.py """Proxy a request to an upstream API using the caller's auth token.""" from golf.auth import get_auth_token import httpx from pydantic import BaseModel class ProxyResult(BaseModel): status_code: int data: dict async def proxy_request(endpoint: str) -> ProxyResult: """Forward the caller's authorization token to an upstream API.""" token = get_auth_token() if not token: return ProxyResult(status_code=401, data={"error": "Unauthorized"}) async with httpx.AsyncClient() as client: resp = await client.get( f"https://upstream.example.com/{endpoint}", headers={"Authorization": f"Bearer {token}"}, timeout=10.0, ) return ProxyResult(status_code=resp.status_code, data=resp.json()) export = proxy_request ``` -------------------------------- ### Manage Golf usage telemetry Source: https://context7.com/golf-mcp/golf/llms.txt Enables or disables anonymous usage telemetry. Telemetry settings are persisted to ~/.golf/telemetry.json. Use --no-telemetry to disable for a single command. ```bash golf telemetry disable golf telemetry enable golf init my-project --no-telemetry ``` -------------------------------- ### proxy_request Source: https://context7.com/golf-mcp/golf/llms.txt Forwards the caller's authorization token to an upstream API endpoint. ```APIDOC ## proxy_request ### Description Forwards the caller's authorization token to an upstream API. ### Method GET ### Endpoint https://upstream.example.com/{endpoint} ### Parameters #### Path Parameters - **endpoint** (string) - Required - The specific API endpoint to proxy the request to. #### Headers - **Authorization** (string) - Required - Bearer token obtained via `get_auth_token()` ### Request Example ```python await proxy_request("users/me") ``` ### Response #### Success Response (200) - **ProxyResult** (object) - Contains the status code and JSON data from the upstream response. - **status_code** (int) - The HTTP status code of the upstream response. - **data** (dict) - The JSON payload from the upstream response. #### Error Response - **ProxyResult** (object) - {"status_code": 401, "data": {"error": "Unauthorized"}} if no token is found. ``` -------------------------------- ### call_upstream Source: https://context7.com/golf-mcp/golf/llms.txt Forwards the user's API key to an upstream service to retrieve data. ```APIDOC ## call_upstream ### Description Forwards the user's API key to an upstream service. ### Method GET ### Endpoint https://api.upstream.example.com/data ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token obtained via `get_api_key()` ### Response #### Success Response (200) - **dict** - JSON response from the upstream service #### Error Response - **dict** - {"error": "No API key provided"} if no API key is found. ``` -------------------------------- ### extract_entities Source: https://context7.com/golf-mcp/golf/llms.txt Extracts named entities (persons, organizations, locations) from text using an LLM and returns them as JSON. ```APIDOC ## extract_entities ### Description Extract named entities (persons, organizations, locations) as JSON. ### Parameters #### Arguments - **text** (string) - Required - The text to extract entities from. ### Response #### Success Response - **EntityResult** (object) - An object containing the extracted entities as a raw JSON string. - **raw_json** (string) - A JSON string with keys "persons", "organizations", "locations", each containing a list of strings. ``` -------------------------------- ### Disable Telemetry for a Specific Command Source: https://github.com/golf-mcp/golf/blob/main/README.md Temporarily disable telemetry for a single command by adding the '--no-telemetry' flag. This preference is saved permanently. ```bash golf init my-project --no-telemetry ```