servicenow-mcp-server

aviro092/servicenow-mcp-server

3.1

If you are the rightful owner of servicenow-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

A Model Context Protocol (MCP) server designed for integrating AI assistants with the ServiceNow incident management system using OAuth2 authentication and Bearer Token security.

Tools
5
Resources
0
Prompts
0

ServiceNow MCP Server

A streamlined Model Context Protocol (MCP) server built with FastMCP for ServiceNow API integration. This server provides AI assistants with tools to interact with ServiceNow's incident management, change requests, and incident tasks using OAuth2 authentication with ServiceNow.

Features

  • 🏗️ Ultra-Simple Architecture: Single-file server with @mcp.tool decorators - no complex imports
  • 🔧 Complete ServiceNow Integration: Full CRUD operations for incidents, change requests, and incident tasks
  • 🔐 OAuth2 Authentication: Secure ServiceNow API authentication with automatic token refresh
  • 🚀 Multiple Transports: Support for stdio, HTTP, and SSE protocols
  • 📋 14 MCP Tools: Comprehensive ServiceNow operations across all major record types
  • 🤖 AI Agent Compatible: HTTP/SSE endpoints for CrewAI, Claude, and other AI frameworks
  • 🐳 Docker Support: Containerized deployment with health checks and MCP Inspector
  • ✅ Type Safety: Pydantic models for data validation and input sanitization
  • 🔄 Retry Logic: Automatic retry with exponential backoff for network failures

Project Structure

servicenow-mcp-server/
├── src/
│   ├── api/                          # ServiceNow API client
│   │   ├── __init__.py
│   │   ├── client.py                 # OAuth2 client with retry logic
│   │   └── exceptions.py             # Custom exception types
│   ├── models/                       # Pydantic data models
│   │   ├── __init__.py
│   │   ├── incident.py               # Incident models
│   │   ├── change_request.py         # Change request models
│   │   └── incident_task.py          # Incident task models
│   ├── tools/                        # Business logic implementations
│   │   ├── __init__.py
│   │   ├── incident_tools.py         # Incident CRUD operations
│   │   ├── change_request_tools.py   # Change request operations
│   │   └── incident_task_tools.py    # Incident task operations
│   ├── __init__.py
│   ├── config.py                     # Configuration management
│   ├── shared_client.py              # Simplified shared ServiceNow client
│   └── fastmcp_server.py             # ✨ Complete server with all 14 tools (executable)
├── docker-compose.yml                # Docker orchestration with MCP Inspector
├── Dockerfile                        # Container definition
├── requirements.txt                  # Python dependencies
├── pyproject.toml                   # Project metadata
├── .env.example                     # Environment template
└── README.md                        # This file

🏗️ Revolutionary Simple Architecture

The server now follows the recommended FastMCP pattern with:

  • ✅ Single Executable File: fastmcp_server.py contains everything - just run it!
  • ✅ Direct @mcp.tool Decorators: No circular imports, no complex handlers
  • ✅ Zero Configuration: Works out of the box with simple imports
  • ✅ 14 Tools in One File: All incident, change request, and task tools included
  • ✅ Clean Pattern: Follows the exact FastMCP documentation example
from fastmcp import FastMCP

mcp = FastMCP("servicenow-mcp")

@mcp.tool
async def get_incident(incident_number: str) -> str:
    """Get incident details from ServiceNow"""
    return result

if __name__ == "__main__":
    mcp.run(transport="http", port=8000)

Requirements

  • Python 3.10+
  • ServiceNow instance with OAuth2 client credentials
  • Docker (optional, for containerized deployment)

Installation

Local Development

  1. Clone the repository:
git clone <repository-url>
cd servicenow-mcp-server
  1. Install dependencies:
pip install -r requirements.txt
  1. Configure environment:
cp .env.example .env
# Edit .env with your ServiceNow credentials

Environment Variables

Create a .env file with the following variables:

# ServiceNow API Configuration
SERVICENOW_BASE_URL=https://yourinstance.service-now.com
SERVICENOW_CLIENT_ID=your_oauth_client_id
SERVICENOW_CLIENT_SECRET=your_oauth_client_secret

# Optional: Override default OAuth token endpoint
# SERVICENOW_TOKEN_ENDPOINT=/oauth_token.do

# API Configuration
SERVICENOW_API_VERSION=v1
SERVICENOW_API_NAMESPACE=x_dusal_cmspapi
SERVICENOW_TIMEOUT=30
SERVICENOW_MAX_RETRIES=3
SERVICENOW_VERIFY_SSL=true

# MCP Server Configuration
MCP_SERVER_NAME=servicenow-mcp
LOG_LEVEL=INFO
ENABLE_DEBUG=false

Usage

Running the Server

HTTP Transport (Default)
python src/fastmcp_server.py
# Or explicitly: python src/fastmcp_server.py --transport http --host 0.0.0.0 --port 8000
Stdio Transport
python src/fastmcp_server.py --transport stdio
SSE Transport
python src/fastmcp_server.py --transport sse --host 0.0.0.0 --port 8000
Help and Options
python src/fastmcp_server.py --help

Docker Deployment

HTTP/SSE Transport (Default)
docker-compose up -d

This starts the ServiceNow MCP Server on port 8000.

With MCP Inspector for Debugging
docker-compose --profile dev up

This starts:

  • ServiceNow MCP Server on port 8000
  • MCP Inspector on port 6274 for testing and debugging
Stdio Transport
docker-compose --profile stdio up servicenow-mcp-stdio
MCP Inspector Access

After starting with --profile dev, access the MCP Inspector at:

API Endpoints (HTTP/SSE Transport)

Core MCP Endpoints

  • Root: http://localhost:8000/ - Server information
  • MCP Protocol: http://localhost:8000/mcp - Main MCP endpoint
  • Tools List: GET request to /mcp with tools/list method
  • Tool Execution: POST request to /mcp with tools/call method

Testing the Server

# Test with curl
curl -X POST http://localhost:8000/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'

Available Tools

The ServiceNow MCP Server provides 14 comprehensive tools across three main categories:

🎫 Incident Management (5 tools)

1. get_incident

Retrieves comprehensive details about a ServiceNow incident.

Parameters:

  • incident_number (string): The incident number (e.g., INC654321)
2. create_incident

Creates a new ServiceNow incident.

Required Parameters:

  • short_description (string): Brief description (max 120 chars)
  • description (string): Full description (max 4000 chars)
  • service_name (string): Service name mapped to cmdb_ci_service table
  • urgency (int): Urgency level (1=Critical, 2=High, 3=Medium, 4=Low)

Optional Parameters:

  • impact, category, subcategory, configuration_item, assigned_to, assignment_group, etc.
3. update_incident

Updates an existing ServiceNow incident.

Required Parameters:

  • incident_number (string): The incident number to update

Optional Parameters:

  • state, impact, urgency, category, subcategory, short_description, description, etc.
4. search_incidents

Searches ServiceNow incidents based on criteria.

Parameters: All optional - active, requested_by, company, service_name, category, state, priority, etc.

5. list_incident_fields

Lists all available incident fields with descriptions and examples.

🔄 Change Request Management (5 tools)

6. search_change_requests

Searches ServiceNow change requests based on criteria.

Parameters: All optional - active, requested_by, company, type, priority, risk, impact, state, etc.

7. get_change_request

Retrieves comprehensive details about a ServiceNow change request.

Parameters:

  • changerequest_number (string): The change request number (e.g., CHG0035060)
8. update_change_request

Updates an existing ServiceNow change request.

Required Parameters:

  • changerequest_number (string): The change request number to update
  • company_name (string): Company name from company record

Optional Parameters:

  • description, comments, on_hold, on_hold_reason, resolved, customer_reference_id
9. approve_change_request

Approves or rejects a change request.

Required Parameters:

  • changerequest_number (string): The change request number
  • state (string): Either 'approved' or 'rejected'
  • approver_email (string): Email of the approver user

Optional Parameters:

  • approver_name, on_behalf
10. list_change_request_fields

Lists all available change request fields with descriptions and examples.

📋 Incident Task Management (4 tools)

11. get_incident_task

Retrieves comprehensive details about a ServiceNow incident task.

Parameters:

  • incident_task_number (string): The incident task number (e.g., TASK0133364)
12. create_incident_task

Creates a new ServiceNow incident task.

Required Parameters:

  • incident_number (string): Parent incident number
  • short_description (string): Task short description (max 120 chars)
  • service_name (string): Service name mapped to cmdb_ci_service table
  • company_name (string): Company name
  • configuration_item (string): Configuration item sys_id

Optional Parameters:

  • description, priority, assignment_group, assigned_to
13. update_incident_task

Updates an existing ServiceNow incident task.

Required Parameters:

  • incident_task_number (string): The task number to update
  • short_description (string): Task short description
  • state (int): Task state (1=New, 2=In Progress, 3=On Hold, 6=Resolved, 7=Closed, 8=Canceled)

Optional Parameters:

  • description, priority, assignment_group, assigned_to
14. list_incident_task_fields

Lists all available incident task fields with descriptions and examples.

📊 Tool Summary

CategoryRead ToolsWrite ToolsTotal
Incidents325
Change Requests325
Incident Tasks224
TOTAL8614

ServiceNow API Integration

The server connects to ServiceNow's custom API endpoints:

  • Base URL: {SERVICENOW_BASE_URL}/api/{namespace}/{version}
  • Incident Endpoint: /itsm/incident/{incident_number}
  • OAuth Token: /oauth_token.do

OAuth2 Flow

  1. Client credentials are exchanged for access token
  2. Token is cached and automatically refreshed before expiration
  3. All API requests include Bearer token authentication

AI Framework Integration

The server runs on HTTP transport by default, making it immediately compatible with AI frameworks:

CrewAI Integration

from crewai import Agent, Task, Crew
import requests

# Example tool call to ServiceNow MCP server
def get_incident_details(incident_number: str):
    response = requests.post("http://localhost:8000/mcp", json={
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "get_incident",
            "arguments": {"incident_number": incident_number}
        }
    })
    return response.json()

Claude MCP Integration

Add to your MCP client configuration:

{
  "mcpServers": {
    "servicenow": {
      "command": "python",
      "args": ["/path/to/servicenow-mcp-server/src/fastmcp_server.py", "--transport", "stdio"]
    }
  }
}

Development

🏗️ Revolutionary Simple Architecture

The server is now incredibly simple - everything in one file:

# ✨ Complete ServiceNow MCP Server in one file
from fastmcp import FastMCP

mcp = FastMCP("servicenow-mcp")

@mcp.tool
async def get_incident(incident_number: str) -> str:
    """Get incident record details by incident number."""
    tools = await get_incident_tools()
    result = await tools.get_incident(incident_number)
    return format_incident_display(result)

# ... 13 more tools ...

if __name__ == "__main__":
    mcp.run(transport="http", port=8000)

Adding New Tools

Adding tools is now incredibly simple:

1. Add Business Logic (Optional)

Create new functions in existing tools/ modules:

# In tools/your_module.py
async def new_operation(self, param: str):
    return await self.client.api_call("/your/endpoint")
2. Add Tool Directly to fastmcp_server.py
@mcp.tool
async def your_new_tool(param: str) -> str:
    """Your tool description."""
    tools = await get_your_tools()
    result = await tools.new_operation(param)
    return str(result)

That's it! The tool automatically registers and is available immediately.

Testing

Test the server with the included test client:

python test_mcp_client.py

Or use the MCP Inspector:

docker-compose --profile dev up
# Open http://localhost:6274

Error Handling

The server includes comprehensive error handling:

  • ServiceNowAuthError: OAuth2 authentication failures
  • ServiceNowNotFoundError: Resource not found (404)
  • ServiceNowRateLimitError: Rate limiting (429)
  • ServiceNowAPIError: General API errors

Logging

Structured logging with:

  • Colored console output for development
  • Contextual error logging
  • API request/response tracking

Security Considerations

  • OAuth2 client credentials stored securely in environment variables
  • SSL verification enabled by default
  • Docker container runs as non-root user
  • Sensitive data is never logged
  • Input validation via Pydantic models

Troubleshooting

Common Issues

  1. OAuth2 Authentication Failed

    • Verify client_id and client_secret are correct
    • Ensure OAuth2 client has necessary permissions
    • Check ServiceNow instance URL
  2. Connection Errors

    • Verify network connectivity to ServiceNow instance
    • Check SSL certificate validity
    • Review proxy settings if applicable
  3. Docker Issues

    • Ensure .env file exists and is readable
    • Check port availability (8000, 6274, 6277)
    • Review Docker logs: docker-compose logs
  4. Tools Not Available

    • Ensure the server started successfully: docker logs servicenow-mcp-server
    • Check the logs for import errors or authentication issues
    • Verify MCP client is connecting to the right URL

Debug Mode

Enable debug logging:

python src/fastmcp_server.py --debug
# Or set environment variable:
LOG_LEVEL=DEBUG python src/fastmcp_server.py

Testing Tools

Use the test client to verify all tools are working:

# Test client should show all 14 tools
python test_mcp_client.py

Expected output:

🛠️  Found 14 tools:
   • get_incident: Get incident record details...
   • list_incident_fields: List all available incident fields...
   • create_incident: Create a new incident record...
   • update_incident: Update incident record...
   • search_incidents: Search incident records...
   • search_change_requests: Search change request records...
   • get_change_request: Get change request record details...
   • list_change_request_fields: List all available change request fields...
   • update_change_request: Update change request record...
   • approve_change_request: Approve or reject a change request...
   • get_incident_task: Get incident task record details...
   • list_incident_task_fields: List all available incident task fields...
   • update_incident_task: Update incident task record...
   • create_incident_task: Create a new incident task record...

License

MIT License - See LICENSE file for details

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test functionality using MCP Inspector or test client
  5. Submit a pull request

Support

For issues or questions:

  • Create an issue in the repository
  • Check existing documentation
  • Use MCP Inspector for debugging: http://localhost:6274 (with --profile dev)
  • Test with the included test client: python test_mcp_client.py