Skip to content

Latest commit

 

History

History
269 lines (213 loc) · 9.89 KB

File metadata and controls

269 lines (213 loc) · 9.89 KB

Sitecore MCP Agent Framework Examples

This folder contains Python examples demonstrating how to use the Microsoft Agent Framework with Sitecore's Model Context Protocol (MCP) server.

Prerequisites

  • Python 3.13+
  • Azure OpenAI resource with API access
  • Sitecore MCP server access (OAuth 2.1 credentials)

Installation

  1. Install required packages:
pip install -r requirements.txt
  1. Configure environment variables:
# Copy the example environment file
cp .env.example .env

# Edit .env with your actual values

Required environment variables in .env:

  • AZURE_OPENAI_ENDPOINT - Your Azure OpenAI endpoint URL
  • AZURE_OPENAI_DEPLOYMENT - Your deployment name (e.g., gpt-5.1-chat)
  • AZURE_OPENAI_API_KEY - Your Azure OpenAI API key
  • AZURE_OPENAI_API_VERSION - API version (default: 2025-01-01-preview)
  1. MCP configuration is already set up in mcp.json:
{
  "mcpServers": {
    "marketer": {
      "url": "https://edge-platform.sitecorecloud.io/mcp/marketer-mcp-prod",
      "auth": {
        "type": "external"
      }
    }
  }
}
  1. Agent instructions are stored in instructions.md:
You are an expert in writing content for the Solterra website.

CRITICAL: You MUST use the Sitecore MCP tools to answer questions about sites, content, and data.
...

The instructions file can be edited to customize agent behavior without modifying code.

Scripts

simple_chat.py

Basic chat example without MCP tools. Uses Azure OpenAI directly for simple conversations.

Usage:

python simple_chat.py

Features:

  • Direct Azure OpenAI integration
  • No MCP tools
  • Simple chat loop

agent_with_mcp.pyRecommended

Complete agent implementation using Sitecore MCP tools via the Agent Framework's built-in MCPStreamableHTTPTool.

Usage:

python agent_with_mcp.py

Features:

  • OAuth 2.1 authentication with PKCE and token caching
  • Automatic MCP tool discovery and integration
  • Uses MCPStreamableHTTPTool for HTTP/SSE transport
  • Streaming responses - See responses word-by-word as they're generated
  • Tool call indicators - Shows 🔧 emoji when MCP tools are being called
  • Automatic conversation history - Maintains context throughout the session
  • Access to 39+ Sitecore tools (site management, content, marketing)

Example queries:

  • "list sites" - List all available Sitecore sites
  • "what languages does the solterra site support?" - Query site details
  • "tell me about the pages in solterra" - Retrieve content information
  • Regular chat works too - the agent knows when to use tools vs. general knowledge

mcp_compliant_auth.py

OAuth 2.1 authentication module for Sitecore MCP server. Used by other scripts.

Features:

  • OAuth 2.1 with PKCE flow
  • Token caching to .mcp_token_cache.json
  • Automatic token refresh
  • Browser-based authentication

⚠️ Security Note: The bearer token is currently cached in .mcp_token_cache.json for development convenience. This is NOT recommended for production environments. For production:

  • Use secure credential storage (Azure Key Vault, etc.)
  • Implement proper token rotation
  • Use managed identities where possible
  • Never commit the token cache file to source control

agent_framework_mcp_auth.py

Note: This approach requires Azure AI Foundry and az login authentication. It uses AzureAIAgentClient with HostedMCPTool, which is Azure AI Foundry-specific and does not support API key authentication.

Use agent_with_mcp.py instead if you want to use API key authentication.


simple_agent_with_mcp.py

Note: This was an experimental manual MCP tool wrapper. The correct approach is to use MCPStreamableHTTPTool as demonstrated in agent_with_mcp.py.

How It Works

1. MCP Authentication Flow

The mcp_compliant_auth.py module handles OAuth 2.1 authentication with PKCE:

  1. Configuration Loading: Reads MCP server URL from mcp.json
  2. Token Cache Check: Looks for valid cached token in .mcp_token_cache.json
  3. OAuth 2.1 Flow (if no valid token):
    • Discovers OAuth endpoints from .well-known/oauth-authorization-server
    • Dynamically registers OAuth client with the server
    • Generates PKCE code challenge and state parameter
    • Opens browser for user authentication at authorization URL
    • Starts local HTTP server on localhost:3000 to receive callback
    • Validates state parameter (CSRF protection)
    • Exchanges authorization code for access token using code verifier
    • Caches token with 24-hour expiration (with 5-minute safety buffer)

⚠️ Token Caching - Development vs Production:

  • Development: Tokens cached in .mcp_token_cache.json (24-hour validity)
  • Production: This approach is NOT recommended. Instead:
    • Use Azure Key Vault or similar secure credential storage
    • Implement proper token rotation and refresh mechanisms
    • Use managed identities where possible
    • Enable audit logging for token access
    • Set shorter token lifetimes
    • Never commit token cache files to source control

2. MCP Tool Integration

The agent_with_mcp.py script uses Agent Framework's built-in MCP support:

  1. Authentication: Gets bearer token via OAuth 2.1 (see section above)
  2. MCPStreamableHTTPTool Setup: Creates tool with:
    • MCP server URL from mcp.json
    • Authorization header with bearer token
    • HTTP/SSE transport for streaming responses
  3. Agent Creation: Creates ChatAgent with:
    • AzureOpenAIChatClient for LLM reasoning
    • MCPStreamableHTTPTool for Sitecore-specific operations
    • Instructions loaded from instructions.md file
  4. Automatic Tool Discovery: Agent:
    • Discovers 39+ available MCP tools from server
    • Automatically calls appropriate tools based on user queries
    • Synthesizes tool results into natural language responses
    • Maintains conversation context across the session

3. Available MCP Tools

The Sitecore MCP server provides tools for:

  • Site Management: List sites, get site details, create/update sites
  • Content Management: Retrieve pages, manage content items
  • Language Support: Query supported languages per site
  • Marketing Operations: Access marketing automation features

Token Caching

File: .mcp_token_cache.json

Format:

{
  "access_token": "Bearer eyJ...",
  "expires_at": "2025-11-20T10:44:06.064319",
  "token_type": "Bearer"
}

Behavior:

  • Tokens are cached with a 5-minute buffer before expiration
  • Cache file is automatically created on first authentication
  • Excluded from git via .gitignore

⚠️ Production Warning: This caching approach is for development only. In production:

  • Store tokens in secure vaults (Azure Key Vault, HashiCorp Vault)
  • Implement proper credential rotation policies
  • Use short-lived tokens with refresh mechanisms
  • Monitor and audit token usage
  • Never store tokens in plain text files

Troubleshooting

"401 Unauthorized" Error

  • Check your AZURE_OPENAI_API_KEY in .env
  • Ensure your Azure OpenAI resource is accessible
  • Verify the endpoint URL is correct (should end in .openai.azure.com)

"MCP Authentication Failed"

  • Check mcp.json OAuth configuration
  • Verify client ID and client secret are correct
  • Ensure redirect URI matches the callback server (default: http://localhost:8888/callback)
  • Delete .mcp_token_cache.json to force re-authentication

"No MCP Tools Available"

  • Check that OAuth token is valid (delete cache and re-authenticate)
  • Verify MCP server URL is accessible
  • Ensure Authorization header is being sent with requests

"Module not found" Errors

  • Run pip install -r requirements.txt
  • Ensure you're using Python 3.13+
  • Check that all dependencies installed successfully

Architecture

┌─────────────────────┐
│   User Input        │
└──────────┬──────────┘
           │
           ▼
┌─────────────────────┐
│   ChatAgent         │
│  (Agent Framework)  │
└──────────┬──────────┘
           │
           ├──────────────────────┐
           ▼                      ▼
┌─────────────────────┐  ┌─────────────────────┐
│ AzureOpenAIChatClient│  │ MCPStreamableHTTPTool│
│  (LLM Reasoning)    │  │  (Sitecore Tools)   │
└─────────────────────┘  └──────────┬──────────┘
                                    │
                                    ▼
                         ┌─────────────────────┐
                         │  Sitecore MCP Server│
                         │  (OAuth Protected)  │
                         └─────────────────────┘

Next Steps

  1. Explore MCP Tools: Run agent_with_mcp.py and ask "what can you do?" to see available capabilities
  2. Review Documentation: Check the Agent Framework MCP guide
  3. Secure Production Deployment: Implement proper credential management before deploying to production
  4. Customize Agent Instructions: Modify the agent's instructions parameter to specialize its behavior

Additional Resources