Microsoft Graph MCP Server
A comprehensive server that enables AI applications to interact with Microsoft 365 and Azure AD services through standardized Model Context Protocol interfaces.
README
Microsoft Graph MCP Server
A comprehensive Model Context Protocol (MCP) server implementation for Microsoft Graph v2 beta API. This server enables AI applications to interact with Microsoft 365 and Azure AD services through standardized MCP interfaces.
Features
Core Capabilities
- Multiple Authentication Methods: Client credentials, device code, interactive browser, managed identity, Azure CLI
- Comprehensive API Coverage: Users, groups, applications, directory roles, and organizational data
- Production Ready: Rate limiting, retry logic, error handling, and async operations
- Configurable: Extensive configuration options with environment variable support
- Secure: Token caching, SSL validation, and permission-based access control
MCP Interfaces
Tools (Direct Operations)
- User Management: List, get, create, update, delete users
- Group Management: List groups, manage members, get group details
- Application Management: List applications and service principals
- Directory Operations: Get organization info, directory roles, and role members
- Utility Tools: Connection testing, service information
Resources (Structured Data Access)
- Static Resources: Current user profile, organization info, service metadata
- Collections: Users, groups, applications with pagination support
- Schemas: Object type definitions for understanding data structures
- Dynamic Resources: Specific users/groups/applications by ID with URI-based access
Prompts (AI Workflows)
- Security Analysis: User profiles, permissions, application security reviews
- Management Workflows: User lifecycle, group membership analysis, role assignments
- Reporting: Inactive users, organizational health checks, compliance reviews
Installation
Prerequisites
- Python 3.10 or higher
- Azure AD application registration with appropriate permissions
- Microsoft 365 or Azure AD tenant access
Install from Source
# Clone the repository
git clone <repository-url>
cd msgraph-mcp
# Install in development mode
pip install -e .
# Or install directly
pip install .
Install Development Dependencies
# Install with development dependencies
pip install -e ".[dev]"
Configuration
Environment Variables
The server can be configured using environment variables with the MSGRAPH_ prefix:
# Required for most authentication methods
export MSGRAPH_TENANT_ID="your-tenant-id"
export MSGRAPH_CLIENT_ID="your-client-id"
export MSGRAPH_CLIENT_SECRET="your-client-secret"
# Optional configuration
export MSGRAPH_AUTH_METHOD="client_credentials" # default
export MSGRAPH_LOG_LEVEL="INFO"
export MSGRAPH_MAX_REQUESTS_PER_SECOND="10"
export MSGRAPH_ENABLE_USER_OPERATIONS="true"
export MSGRAPH_ENABLE_GROUP_OPERATIONS="true"
Configuration File
Create a .env file in your working directory:
# Azure AD Configuration
MSGRAPH_TENANT_ID=your-tenant-id
MSGRAPH_CLIENT_ID=your-application-client-id
MSGRAPH_CLIENT_SECRET=your-client-secret
MSGRAPH_AUTH_METHOD=client_credentials
# API Configuration
MSGRAPH_GRAPH_BASE_URL=https://graph.microsoft.com/beta
MSGRAPH_MAX_REQUESTS_PER_SECOND=10
MSGRAPH_REQUEST_TIMEOUT=30
# Feature Toggles
MSGRAPH_ENABLE_USER_OPERATIONS=true
MSGRAPH_ENABLE_GROUP_OPERATIONS=true
MSGRAPH_ENABLE_APPLICATION_OPERATIONS=true
MSGRAPH_ENABLE_DIRECTORY_OPERATIONS=true
MSGRAPH_ENABLE_MAIL_OPERATIONS=false
MSGRAPH_ENABLE_CALENDAR_OPERATIONS=false
MSGRAPH_ENABLE_TEAMS_OPERATIONS=false
# Logging
MSGRAPH_LOG_LEVEL=INFO
MSGRAPH_ENABLE_DEBUG_LOGGING=false
Authentication Methods
1. Client Credentials (Service-to-Service)
export MSGRAPH_AUTH_METHOD="client_credentials"
export MSGRAPH_TENANT_ID="your-tenant-id"
export MSGRAPH_CLIENT_ID="your-client-id"
export MSGRAPH_CLIENT_SECRET="your-client-secret"
2. Device Code Flow
export MSGRAPH_AUTH_METHOD="device_code"
export MSGRAPH_TENANT_ID="your-tenant-id"
export MSGRAPH_CLIENT_ID="your-client-id"
3. Interactive Browser
export MSGRAPH_AUTH_METHOD="interactive"
export MSGRAPH_TENANT_ID="your-tenant-id"
export MSGRAPH_CLIENT_ID="your-client-id"
4. Managed Identity (Azure)
export MSGRAPH_AUTH_METHOD="managed_identity"
# No additional configuration needed when running on Azure
5. Azure CLI
export MSGRAPH_AUTH_METHOD="azure_cli"
# Requires 'az login' to be completed
Usage
Command Line Interface
# Start the MCP server
msgraph-mcp
# Test configuration and connection
msgraph-mcp --test-config
# Run with debug logging
msgraph-mcp --log-level DEBUG --debug
# Use custom configuration file
msgraph-mcp --config-file /path/to/custom.env
Programmatic Usage
import asyncio
from msgraph_mcp import MCPGraphServer, GraphConfig
async def main():
# Create configuration
config = GraphConfig(
tenant_id="your-tenant-id",
client_id="your-client-id",
client_secret="your-client-secret",
auth_method="client_credentials"
)
# Create and run server
server = MCPGraphServer(config)
await server.run()
if __name__ == "__main__":
asyncio.run(main())
Integration with MCP Clients
The server implements the standard MCP protocol and can be used with any MCP-compatible client:
{
"mcpServers": {
"msgraph": {
"command": "msgraph-mcp",
"env": {
"MSGRAPH_TENANT_ID": "your-tenant-id",
"MSGRAPH_CLIENT_ID": "your-client-id",
"MSGRAPH_CLIENT_SECRET": "your-client-secret"
}
}
}
}
Azure AD Application Setup
Required Permissions
Your Azure AD application needs the following Microsoft Graph permissions:
Application Permissions (for service-to-service scenarios)
User.Read.All- Read all user profilesGroup.Read.All- Read all groupsApplication.Read.All- Read all applicationsDirectory.Read.All- Read directory dataOrganization.Read.All- Read organization information
Delegated Permissions (for user-context scenarios)
User.Read- Read user profileUser.ReadWrite.All- Read and write all user profilesGroup.ReadWrite.All- Read and write all groupsDirectory.AccessAsUser.All- Access directory as user
Grant Admin Consent
After configuring permissions, ensure admin consent is granted for your tenant.
API Examples
Using Tools
# List users
result = await server.call_tool("list_users", {
"top": 10,
"select": "displayName,mail,jobTitle"
})
# Get specific user
result = await server.call_tool("get_user", {
"user_id": "user@company.com",
"select": "displayName,mail,department"
})
# Create user
result = await server.call_tool("create_user", {
"display_name": "John Doe",
"user_principal_name": "john.doe@company.com",
"mail_nickname": "johndoe",
"password": "TempPassword123!"
})
Using Resources
# Get current user profile
profile = await server.get_resource("msgraph://me")
# Get users collection
users = await server.get_resource("msgraph://users?top=50&select=displayName,mail")
# Get specific group members
members = await server.get_resource("msgraph://groups/group-id/members")
Using Prompts
# Analyze user profile for security issues
analysis = await server.get_prompt("analyze_user_profile", {
"user_id": "user@company.com"
})
# Generate inactive users report
report = await server.get_prompt("inactive_users_report", {
"days_threshold": "90"
})
Development
Project Structure
src/msgraph_mcp/
├── __init__.py # Package initialization
├── __main__.py # CLI entry point
├── server.py # Main MCP server implementation
├── config.py # Configuration management
├── auth.py # Authentication handling
├── graph_client.py # Microsoft Graph client
├── tools.py # MCP tools implementation
├── resources.py # MCP resources implementation
└── prompts.py # MCP prompts implementation
Running Tests
# Run all tests
pytest
# Run with coverage
pytest --cov=msgraph_mcp
# Run specific test file
pytest tests/test_server.py
Code Quality
# Format code
black src/ tests/
# Lint code
ruff check src/ tests/
# Type checking
mypy src/
Security Considerations
- Credential Management: Never commit secrets to version control
- Least Privilege: Only enable required feature toggles and permissions
- Network Security: Use SSL validation in production
- Token Security: Tokens are cached securely and refreshed automatically
- Rate Limiting: Built-in rate limiting prevents API abuse
Troubleshooting
Common Issues
Authentication Errors
# Test your configuration
msgraph-mcp --test-config
# Check Azure AD app permissions and admin consent
# Verify tenant ID, client ID, and client secret
Permission Errors
# Verify your app has the required Microsoft Graph permissions
# Ensure admin consent has been granted
# Check that feature toggles match your permissions
Rate Limiting
# Adjust rate limiting settings
export MSGRAPH_MAX_REQUESTS_PER_SECOND=5
export MSGRAPH_MAX_CONCURRENT_REQUESTS=3
Debug Logging
Enable debug logging to troubleshoot issues:
msgraph-mcp --log-level DEBUG --debug
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
License
MIT License - see LICENSE file for details.
Support
For issues and questions:
- Check the troubleshooting section
- Review Microsoft Graph documentation
- Open an issue on the repository
- Check Azure AD application configuration
Note: This implementation uses Microsoft Graph v2 beta endpoints. Some features may change or require different permissions as Microsoft updates their API.
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。