> ## Documentation Index
> Fetch the complete documentation index at: https://docs.spikeapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Integration Guide

> Complete implementation examples for integrating Spike's MCP server with AI providers

Integrate Spike's health data into AI applications using the Model Context Protocol (MCP). The examples below show complete implementations for OpenAI and Anthropic clients, including authentication, server configuration, and data querying.

<Info>
  **Requirements:**

  * Spike JWT access token (see [Authentication](/api-docs/authentication))
  * AI provider API key (OpenAI or Anthropic)
  * MCP server URL: `https://app-api.spikeapi.com/v3/mcp`
</Info>

```mermaid theme={null}
sequenceDiagram
    participant UserApp as User Application
    participant Provider as AI Provider (e.g., OpenAI/Anthropic)
    participant MCP as MCP Server (Spike Health Data)
    
    UserApp->>UserApp: Load OPENAI_API_KEY/\nSPIKE_ACCESS_TOKEN
    UserApp->>Provider: Authenticate with API Key
    UserApp->>MCP: Configure MCP tool (JWT, URL)\nset as available tool for Provider
    UserApp->>Provider: Request health data analysis\n(e.g., Analyze my sleep data...)
    
    Provider->>MCP: API request with Authorization: Bearer SPIKE_ACCESS_TOKEN
    MCP-->>Provider: User health data analysis/insights
    Provider-->>UserApp: Return analysis, tokens used, etc.

    Note over UserApp,Provider: Error handling if missing\nAPI Key or Token

```

### Using the Token

Include the JWT token in the Authorization header when configuring the MCP tool:

```
Authorization: Bearer <your_jwt_token>
```

## OpenAI

<CodeGroup>
  ```bash [Curl] theme={null}
  curl -X POST "https://api.openai.com/v1/responses" \
    -H "Authorization: Bearer OPENAPI_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "o4-mini",
      "instructions": "you are a health and wellness analyst.",
      "input": "Analyze my health data for 2025-08-17 and provide a summary of my health data.",
      "tools": [
        {
          "type": "mcp",
          "server_label": "spike-health-data",
          "server_url": "https://app-api.spikeapi.com/v3/mcp",
          "headers": {
            "Authorization": "Bearer SPIKE_ACCESS_TOKEN"
          },
          "server_description": "Health and fitness data analysis server providing daily and hourly statistics from connected wearables and health devices.",
          "require_approval": "never"
        }
      ],
      "tool_choice": "auto",
      "max_tool_calls": 1,
      "max_output_tokens": 5000,
      "parallel_tool_calls": true,
      "metadata": {
        "analysis_type": "daily_health_review",
        "date": "2025-08-17",
        "tools_used": "mcp_health_data",
        "version": "1.0.0"
      }
    }'
  ```

  ```go [Go] theme={null}
  package main

  import (
  	"context"
  	"fmt"
  	"log"
  	"os"

  	openai "github.com/openai/openai-go/v2"
  	"github.com/openai/openai-go/v2/option"
  	"github.com/openai/openai-go/v2/responses"
  )

  func main() {
  	// Required environment variables
  	openaiKey := os.Getenv("OPENAI_API_KEY")
  	spikeToken := os.Getenv("SPIKE_ACCESS_TOKEN")

  	if openaiKey == "" || spikeToken == "" {
  		log.Fatal("OPENAI_API_KEY and SPIKE_ACCESS_TOKEN environment variables are required")
  	}

  	// Create OpenAI client
  	client := openai.NewClient(option.WithAPIKey(openaiKey))

  	// Configure the SpikeAI MCP tool
  	mcpTool := responses.ToolUnionParam{
  		OfMcp: &responses.ToolMcpParam{
  			Type:        "mcp",
  			ServerLabel: "spike-health-data",
  			ServerURL:   "https://app-api.spikeapi.com/v3/mcp",
  			Headers: map[string]string{
  				"Authorization": fmt.Sprintf("Bearer %s", spikeToken),
  			},
  			ServerDescription: openai.String("Health and fitness data analysis server"),
  			RequireApproval: responses.ToolMcpRequireApprovalUnionParam{
  				OfMcpToolApprovalSetting: openai.String("never"),
  			},
  		},
  	}

  	// Create the chat request
  	request := responses.ResponseNewParams{
  		Model:        responses.ChatModelO4Mini,
  		Instructions: openai.String("You are a health data analyst. Use the available tools to analyze the user's health data and provide insights."),
  		Input: responses.ResponseNewParamsInputUnion{
  			OfString: openai.String("Analyze my sleep data for the past 3 days and give me a brief summary of my sleep patterns."),
  		},
  		Tools: []responses.ToolUnionParam{mcpTool},
  		ToolChoice: responses.ResponseNewParamsToolChoiceUnion{
  			OfToolChoiceMode: openai.Opt(responses.ToolChoiceOptionsAuto),
  		},
  		MaxOutputTokens:   openai.Opt(int64(1000)),
  		MaxToolCalls:      openai.Opt(int64(3)),
  		ParallelToolCalls: openai.Opt(true),
  	}

  	// Make the API call
  	ctx := context.Background()
  	response, err := client.Responses.New(ctx, request)
  	if err != nil {
  		log.Fatalf("API call failed: %v", err)
  	}

  	// Print the response
  	fmt.Println("=== Health Data Analysis ===")
  	fmt.Println(response.OutputText())

  	// Print usage statistics
  	fmt.Printf("\nTokens used - Input: %d, Output: %d, Total: %d\n",
  		response.Usage.InputTokens,
  		response.Usage.OutputTokens,
  		response.Usage.TotalTokens)
  }

  ```

  ```python [Python] theme={null}
  import os
  import sys
  from openai import OpenAI

  def main():
      # Required environment variables
      openai_key = os.getenv("OPENAI_API_KEY")
      spike_token = os.getenv("SPIKE_ACCESS_TOKEN")
      
      if not openai_key or not spike_token:
          print("Error: OPENAI_API_KEY and SPIKE_ACCESS_TOKEN environment variables are required")
          sys.exit(1)
      
      # Create OpenAI client
      client = OpenAI(api_key=openai_key)
      
      # Configure the SpikeAI MCP tool
      mcp_tool = {
          "type": "mcp",
          "server_label": "spike-health-data",
          "server_url": "https://app-api.spikeapi.com/v3/mcp",
          "headers": {
              "Authorization": f"Bearer {spike_token}"
          },
          "server_description": "Health and fitness data analysis server",
          "require_approval": "never"
      }
      
      try:
          # Create the responses request
          response = client.responses.create(
              model="gpt-4o",
              input=[
                  {
                      "role": "user", 
                      "content": "Analyze my sleep data for the past 3 days and give me a brief summary of my sleep patterns."
                  }
              ],
              instructions="You are a health data analyst. Use the available tools to analyze the user's health data and provide insights.",
              tools=[mcp_tool],
              max_tokens=1000
          )
          
          # Print the response
          print("=== Health Data Analysis ===")
          print(response.output[0].content)
          
          # Print usage statistics if available
          if hasattr(response, 'usage'):
              usage = response.usage
              print(f"\nTokens used - Input: {usage.prompt_tokens}, Output: {usage.completion_tokens}, Total: {usage.total_tokens}")
          
      except Exception as e:
          print(f"API call failed: {e}")
          sys.exit(1)

  if __name__ == "__main__":
      main()
  ```

  ```typescript [Node.js] theme={null}
  const openaiKey = process.env.OPENAI_API_KEY;
  const spikeToken = process.env.SPIKE_ACCESS_TOKEN;

  if (!openaiKey || !spikeToken) {
      console.error('Error: OPENAI_API_KEY and SPIKE_ACCESS_TOKEN environment variables are required');
      process.exit(1);
  }

  // Create OpenAI client
  const client = new OpenAI({
      apiKey: openaiKey
  });

  // Configure the SpikeAI MCP tool
  const mcpTool = {
      type: 'mcp',
      server_label: 'spike-health-data',
      server_url: 'https://app-api.spikeapi.com/v3/mcp',
      headers: {
          'Authorization': `Bearer ${spikeToken}`
      },
      server_description: 'Health and fitness data analysis server',
      require_approval: 'never'
  };

  try {
      // Create the response request using the new responses API
      const response = await client.responses.create({
          model: 'o1-mini',
          instructions: 'You are a health data analyst. Use the available tools to analyze the user\'s health data and provide insights.',
          input: 'Analyze my sleep data for the past 3 days and give me a brief summary of my sleep patterns.',
          tools: [mcpTool],
          tool_choice: 'auto',
          max_output_tokens: 1000,
          max_tool_calls: 3,
          parallel_tool_calls: true
      });
      
      // Print the response
      console.log('=== Health Data Analysis ===');
      console.log(response.output_text);
      
      // Print usage statistics
      const usage = response.usage;
      console.log(`\nTokens used - Input: ${usage.input_tokens}, Output: ${usage.output_tokens}, Total: ${usage.total_tokens}`);
      
  } catch (error) {
      console.error(`API call failed: ${error.message}`);
      process.exit(1);
  }
  ```
</CodeGroup>

## Anthropic

<CodeGroup>
  ```bash [Curl] theme={null}
  curl https://api.anthropic.com/v1/messages \
    -H "Content-Type: application/json" \
    -H "X-API-Key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "anthropic-beta: mcp-client-2025-04-04" \
    -d '{
      "model": "claude-sonnet-4-20250514",
      "max_tokens": 1024,
      "mcp_servers": [
        {
          "type": "url",
          "name": "spike-health-data",
          "url": "https://app-api.spikeapi.com/v3/mcp",
          "authorization_token": "SPIKE_ACCESS_TOKEN",
          "tool_configuration": {
            "enabled": true,
          }
        }
      ],
      "messages": [
        {
          "role": "user",
          "content": "Analyze my health data for 2025-08-17 and provide a summary of my health data."
        }
      ]
    }'
  ```

  ```python [Python] theme={null}
  import os
  import sys
  from anthropic import Anthropic

  def main():
      # Required environment variables
      anthropic_key = os.getenv("ANTHROPIC_API_KEY")
      spike_token = os.getenv("SPIKE_ACCESS_TOKEN")
      
      if not anthropic_key or not spike_token:
          print("Error: ANTHROPIC_API_KEY and SPIKE_ACCESS_TOKEN environment variables are required")
          sys.exit(1)
      
      # Create Anthropic client
      client = Anthropic(api_key=anthropic_key)
      
      try:
          # Create the message request using MCP server
          response = client.beta.messages.create(
              model="claude-3-5-sonnet-20241022",
              max_tokens=1000,
              messages=[
                  {
                      "role": "user",
                      "content": "You are a health data analyst. Analyze my sleep data for the past 3 days and give me a brief summary of my sleep patterns.",
                  }
              ],
              mcp_servers=[
                  {
                      "type": "url",
                      "url": "https://app-api.spikeapi.com/v3/mcp",
                      "authorization_token": spike_token,
                      "name": "spike-health-data",
                      "tool_configuration": {
                          "enabled": True,
                      },
                  }
              ],
              extra_headers={
                  "anthropic-beta": "mcp-client-2025-04-04",
              },
          )
          
          # Print the response
          print("=== Health Data Analysis ===")
          for content_block in response.content:
              if content_block.type == "text":
                  print(content_block.text)
          
          # Print usage statistics
          usage = response.usage
          print(f"\nTokens used - Input: {usage.input_tokens}, Output: {usage.output_tokens}")
          
      except Exception as e:
          print(f"API call failed: {e}")
          sys.exit(1)

  if __name__ == "__main__":
      main()
  ```
</CodeGroup>
