npm package: @iimransarwar/sharepoint-mcp
Description: SharePoint MCP is a Model Context Protocol (MCP) server for Microsoft Graph with enhanced search, metadata extraction, pagination, and caching.
Author: Imran Sarwar
Latest version: 0.0.41

# SharePoint MCP Server

[![Version](https://img.shields.io/npm/v/@iimransarwar/sharepoint-mcp)](https://www.npmjs.com/package/@iimransarwar/sharepoint-mcp)
[![Security](https://img.shields.io/badge/Security-Enterprise%20Grade-green)](./SECURITY_REVIEW.md)
[![JWT Validation](https://img.shields.io/badge/JWT-Cryptographically%20Verified-success)](./jwt-validator.ts)

## 📋 Overview

SharePoint MCP Server is an enterprise-grade Model Context Protocol (MCP) server that enables AI assistants like Claude to interact with Microsoft Graph and Azure Resource Management APIs. This allows you to manage your Microsoft 365 and Azure resources using natural language through any MCP-compatible client.

**Version 0.0.35 Update**: Added powerful document parsing capabilities, smart pagination, and enhanced file handling with direct file ID support.

### Key Features

- 🔐 **Multiple Authentication Methods**: Support for interactive, client credentials, and certificate-based authentication
- 🛡️ **Enterprise Security**: 
  - Cryptographic JWT validation with JWKS
  - Zero Trust monitoring (Level 0.5)
  - Token Revocation List (TRL)
  - Emergency kill switch and read-only modes
  - Rate limiting and audit logging
- 🔒 **Token Security**: 
  - JWT signature verification against Microsoft's public keys
  - Automatic JWKS key rotation
  - Token expiration and claims validation
  - Protection against token forgery and replay attacks
- 🔑 **Encrypted Token Cache**: Secure token persistence across restarts with AES-256-GCM encryption
- 📊 **Full Microsoft Graph Support**: Access to users, groups, SharePoint, Teams, and more
- ☁️ **Azure Resource Management**: Manage Azure subscriptions and resources
- 🔄 **Pagination Support**: Automatic handling of large datasets
- 📝 **Comprehensive Audit Trail**: Track all sensitive operations for compliance
- 🔍 **SharePoint Site Discovery**: New tool to discover, search, and filter SharePoint sites
- 📁 **Enhanced SharePoint Operations**: Advanced file search, metadata extraction, and smart pagination
- 📄 **Document Parsing**: Extract text from PDF, Excel, PowerPoint, HTML, RTF, and text files
- 🎯 **Direct File ID Support**: Access files using SharePoint file IDs for faster operations
- 📊 **Smart Pagination**: Automatic context-aware pagination to prevent overwhelming LLM context windows

## 🌐 Supported Microsoft Services

### 📈 Microsoft Dynamics 365 (Limited Support via Graph API)

**Note**: The MCP Server currently provides **limited** Dynamics 365 access through Microsoft Graph API endpoints only. Full Dynamics 365 Web API and Dataverse access would require additional implementation.

#### Currently Supported Dynamics 365 Operations:

**Via Microsoft Graph API (`/beta/` endpoints):**
- **Basic CRM Data Access**
  - Read customer and contact information (if exposed via Graph)
  - Access business contacts synchronized with Exchange
  - Query user relationships and organizational data

**Power Platform Integration (via Graph):**
- **Power Automate Flows**
  - List and trigger flows associated with the user
  - Access flow run history
- **Limited Dataverse Access**
  - Only for entities exposed through Graph API
  - Basic CRUD operations on select entities

#### 🚫 NOT Currently Supported (Would Require Direct Dynamics 365 API):

- Direct Dataverse/Common Data Service operations
- Full Dynamics 365 Sales, Service, Marketing, Field Service modules
- Custom entity operations
- Business process flows
- Advanced CRM operations (opportunities, leads, cases)
- Finance & Operations data
- Business Central ERP functions

#### 🔄 Workaround for Extended Dynamics 365 Access:

To access full Dynamics 365 capabilities, you can use the generic `microsoft-graph` tool with appropriate endpoints:

```javascript
// Example: Access Dynamics 365 data if exposed via Graph Beta API
{
  "tool": "microsoft-graph",
  "apiType": "graph",
  "path": "/beta/me/contacts",  // Business contacts
  "method": "get",
  "graphApiVersion": "beta"
}
```

**Important**: Most Dynamics 365 operations require the Dynamics 365 Web API (`https://[org].crm.dynamics.com/api/data/v9.2/`) which is **not** currently implemented in this MCP Server. The server would need to be extended to support Dataverse Web API endpoints for full Dynamics 365 functionality.

### Core Microsoft Graph Services

#### 📁 SharePoint & OneDrive (Enhanced in v0.0.24)

**Site Discovery & Management** (NEW):
- **`sharepoint-site-discovery` tool**: Comprehensive site discovery with multiple operations:
  - `list_all` - List all accessible SharePoint sites
  - `search` - Search sites by name or description
  - `my_sites` - Get user's followed or recently accessed sites
  - `hub_sites` - List SharePoint hub sites
  - `team_sites` - List team sites connected to Microsoft 365 groups
  - `communication_sites` - List communication sites
- **Site filtering**: Filter by site type, creation date, and more
- **Subsites discovery**: Optionally include subsites in results
- **Site details**: Get storage quota, document library counts, and list counts

**File Operations** (`sharepoint-site-files` tool):
- **Advanced search**: Search files with multiple filters:
  - By file type, modified date, creator, size
  - Within specific folders or entire sites
  - Using Microsoft Search API for better relevance
- **Bulk operations**: List, filter, and process multiple files
- **Metadata extraction**: Get comprehensive file metadata including:
  - Version history, sharing status, permissions
  - Image/video metadata, compliance labels
  - Analytics and activity data
- **Smart pagination**: Handle large folders efficiently
- **Special operations**:
  - Find recently modified files
  - Locate large files consuming storage
  - Identify shared files and their permissions
  - Browse folder structures

**Document Parsing** (`file-parser` tool) - NEW in v0.0.35:
- **Multi-format support**: Parse documents without external dependencies:
  - PDF files (using pdfjs-dist)
  - Excel spreadsheets (.xlsx, .xls, .xlsm)
  - PowerPoint presentations (.pptx, .ppt)
  - HTML documents
  - RTF documents
  - Plain text files (txt, md, json, xml, csv, yaml)
- **Flexible file access**:
  - Direct file ID support: `fileId: "01B65XAEES6VTGM5KFC5AYMZJX4RXAEMNN"`
  - Path-based access: `filePath: "/Documents/folder/file.pdf"`
  - Auto-detection of misplaced file IDs
- **Operations**:
  - `parse`: Extract full text content for LLM analysis
  - `summarize`: Get document summary with key metadata
  - `metadata`: Extract only document metadata
- **Smart features**:
  - Automatic file type detection
  - Metadata extraction (author, title, creation date, page count)
  - Large file handling without memory issues
  - Clear error messages with troubleshooting guidance

**Performance Features**:
- **Smart pagination**: Default 10 items per request to protect LLM context
- **Caching system**: Multi-layer caching for improved performance
- **Batch operations**: Process multiple files in single requests
- **Iterator patterns**: Stream large datasets without memory issues
- **Context protection**: Automatic limits on result sizes with continuation tokens

**Core SharePoint Capabilities**:
- **Access and manage SharePoint sites**: List, create, and modify SharePoint sites
- **Document management**: Upload, download, update, and delete files
- **List operations**: Create and manage SharePoint lists and list items
- **Drive operations**: Access OneDrive files and folders
- **Permissions management**: Configure sharing and access permissions
- **Search capabilities**: Search across sites and documents

#### 👥 Users & Groups
- **User management**: Query, create, update, and delete users
- **Group operations**: Manage Microsoft 365 groups and security groups
- **Directory queries**: Search and filter users by various attributes
- **Profile information**: Access user profiles, photos, and presence
- **Manager relationships**: Query reporting structures

#### 💬 Microsoft Teams
- **Team management**: Create and configure teams
- **Channel operations**: Manage channels and tabs
- **Member management**: Add/remove team members and owners
- **Chat capabilities**: Access team conversations
- **App integration**: Configure Teams apps and tabs

#### 📧 Outlook/Exchange
- **Email operations**: Read, send, and manage emails
- **Calendar management**: Access and modify calendar events
- **Contact management**: Manage contacts and contact folders
- **Mail folders**: Organize and search mail folders

#### 📝 OneNote
- **Notebook management**: Create and organize notebooks
- **Section operations**: Manage notebook sections
- **Page content**: Create and update notes
- **Search functionality**: Search across all notes

### Azure Services Integration

#### ☁️ Azure Resource Management
- **Subscription management**: List and manage Azure subscriptions
- **Resource operations**: Create, update, and delete Azure resources
- **Resource groups**: Organize and manage resource groups
- **Cost management**: Access billing and usage information

#### 🔐 Azure Key Vault
- **Secret management**: Store and retrieve secrets
- **Key operations**: Manage encryption keys
- **Certificate handling**: Store and manage certificates
- **Access policies**: Configure vault access permissions

#### 💾 Azure Storage
- **Blob storage**: Upload and manage blob containers
- **File shares**: Access Azure Files
- **Queue operations**: Manage storage queues
- **Table storage**: Work with structured NoSQL data

#### 🔑 Azure Active Directory
- **Identity management**: Manage users and groups
- **App registrations**: Configure application identities
- **Role assignments**: Manage RBAC permissions
- **Conditional access**: Configure security policies

### Microsoft 365 Administration

#### 🛡️ Security & Compliance
- **Conditional access policies**: Configure and manage access rules
- **Audit logs**: Access security and compliance logs
- **Data loss prevention**: Configure DLP policies
- **Information protection**: Manage sensitivity labels

#### 📱 Intune/Device Management
- **Device enrollment**: Manage device registration
- **Configuration profiles**: Deploy device configurations
- **Compliance policies**: Set and monitor compliance rules
- **App deployment**: Distribute and manage applications

#### 📊 Power Platform
- **Power Automate**: Access flow templates and manage workflows
- **Power Apps**: Interact with business applications
- **Dataverse**: Access business data platform

#### 📈 Future Dynamics 365 Support
Full support for Dynamics 365 modules would require implementing the Dataverse Web API. This would enable:
- Project Operations, Commerce, Fraud Protection
- Customer Insights (CDP)
- Complete Sales, Service, Marketing, and Field Service access
- Custom entity and business process management

### Advanced Capabilities

#### 🔍 Microsoft Search
- **Universal search**: Search across all Microsoft 365 content
- **Custom search verticals**: Configure specialized search experiences
- **Search analytics**: Access search usage insights

#### 📊 Analytics & Reporting
- **Usage analytics**: Access Microsoft 365 usage reports
- **Activity reports**: Monitor user and admin activities
- **Security reports**: Review security incidents and alerts

#### 🤖 AI & Cognitive Services
- **Microsoft Purview**: Data governance and compliance
- **Azure Cognitive Services**: When integrated with Azure
- **Microsoft Viva**: Employee experience platform access

### What You Can Do With These Services

- **Automate workflows**: Create automated processes across Microsoft 365
- **Bulk operations**: Perform mass updates on users, groups, or resources
- **Cross-service integration**: Connect data between different Microsoft services
- **Compliance management**: Ensure organizational compliance with policies
- **Security monitoring**: Track and respond to security events
- **Resource optimization**: Analyze and optimize Azure resource usage
- **Collaboration enhancement**: Streamline team collaboration processes
- **Data migration**: Move data between services or accounts
- **Custom reporting**: Generate tailored reports from multiple data sources
- **Incident response**: Quickly respond to security or operational incidents

## 🚀 Quick Start

### Installation

Install the MCP server globally via npm:

```bash
npm install -g @iimransarwar/sharepoint-mcp
```

Or use it directly with npx (recommended):

```bash
npx @iimransarwar/sharepoint-mcp
```

## 🔑 Authentication Methods

The SharePoint MCP Server supports three authentication methods. Choose the one that best fits your security requirements and use case.

### Method 1: Interactive Authentication (Easiest for Development)

**Best for**: Development, testing, and personal use where browser-based authentication is acceptable.

#### Configuration

```json
{
  "sharepoint-mcp": {
    "command": "npx",
    "args": ["-y", "@iimransarwar/sharepoint-mcp"],
    "env": {
      "USE_INTERACTIVE": "true",
      "TENANT_ID": "your-tenant-id",    // Optional: defaults to "common"
      "CLIENT_ID": "your-client-id"     // Optional: uses default app
    }
  }
}
```

#### How It Works
- Opens a browser window for authentication when the server starts
- Uses your personal Microsoft account permissions
- Tokens expire after ~1 hour and require re-authentication
- Supports multi-factor authentication (MFA)

#### Pros & Cons
✅ Easy to set up - no app registration required  
✅ Uses your existing permissions  
✅ Supports MFA  
❌ Requires browser interaction on each restart  
❌ Not suitable for automation  

---

### Method 2: Client Credentials (Recommended for Production)

**Best for**: Production environments, automation, and scenarios where the app needs its own identity.

#### Step 1: Create an Azure AD App Registration

1. Go to [Azure Portal](https://portal.azure.com) → Azure Active Directory → App registrations
2. Click "New registration"
3. Enter a name (e.g., "SharePoint MCP Server")
4. Select "Accounts in this organizational directory only"
5. Click "Register"
6. Copy the **Application (client) ID** and **Directory (tenant) ID**

#### Step 2: Create a Client Secret

1. In your app registration, go to "Certificates & secrets"
2. Click "New client secret"
3. Add a description and select expiration period
4. Click "Add"
5. **IMPORTANT**: Copy the secret VALUE immediately (not the ID)

#### Step 3: Add API Permissions

1. Go to "API permissions" → "Add a permission"
2. Choose "Microsoft Graph" → "Application permissions"
3. Add required permissions based on your needs:

**Common Permissions**:
- `User.Read.All` - Read all users
- `Group.Read.All` - Read all groups
- `Sites.Read.All` - Read SharePoint sites
- `Sites.ReadWrite.All` - Modify SharePoint content
- `Mail.Read` - Read emails
- `Directory.Read.All` - Read directory data

4. **CRITICAL**: Click "Grant admin consent" (requires admin rights)

#### Step 4: Configure MCP

```json
{
  "sharepoint-mcp": {
    "command": "npx",
    "args": ["-y", "@iimransarwar/sharepoint-mcp"],
    "env": {
      "TENANT_ID": "12345678-1234-1234-1234-123456789012",
      "CLIENT_ID": "87654321-4321-4321-4321-210987654321",
      "CLIENT_SECRET": "xWd8Q~1aB2cD3eF4gH5iJ6kL7mN8oP9qR0sT"
    }
  }
}
```

#### Pros & Cons
✅ No user interaction required  
✅ Perfect for automation  
✅ Runs continuously without re-authentication  
✅ Can be granted specific permissions  
❌ Requires admin consent for permissions  
❌ Acts as an app, not a user  

---

### Method 3: Certificate Authentication (Most Secure)

**Best for**: High-security environments requiring certificate-based authentication.

#### Step 1: Generate a Certificate

```bash
# Generate a private key and certificate
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes

# Combine into a single PEM file
cat cert.pem key.pem > appcert.pem

# Extract the public certificate for Azure
openssl x509 -in cert.pem -outform DER -out cert.cer
```

#### Step 2: Upload Certificate to Azure AD

1. Go to your app registration in Azure Portal
2. Navigate to "Certificates & secrets" → "Certificates"
3. Click "Upload certificate"
4. Upload the `cert.cer` file
5. Note the thumbprint displayed

#### Step 3: Configure MCP

```json
{
  "sharepoint-mcp": {
    "command": "npx",
    "args": ["-y", "@iimransarwar/sharepoint-mcp"],
    "env": {
      "TENANT_ID": "12345678-1234-1234-1234-123456789012",
      "CLIENT_ID": "87654321-4321-4321-4321-210987654321",
      "USE_CERTIFICATE": "true",
      "CERTIFICATE_PATH": "/secure/path/to/appcert.pem",
      "CERTIFICATE_PASSWORD": "optional-password-if-encrypted"
    }
  }
}
```

#### Pros & Cons
✅ Most secure authentication method  
✅ No secrets in configuration  
✅ Certificates can be managed centrally  
✅ Supports certificate rotation  
❌ More complex setup  
❌ Requires certificate management  

## 🛠️ Available Tools

### Core Tools

#### 1. `microsoft-graph`
Universal tool for Microsoft Graph and Azure Resource Management API calls.
- **Parameters**: `apiType`, `path`, `method`, `body`, `queryParams`
- **Features**: Automatic pagination, retry logic, streaming support

#### 2. `sharepoint-site-discovery`
Discover and search SharePoint sites across your organization.
- **Operations**: `list_all`, `search`, `my_sites`, `hub_sites`, `team_sites`, `communication_sites`
- **Smart Features**: Summary mode for large results, continuation tokens

#### 3. `sharepoint-site-files`
Advanced file operations on SharePoint sites.
- **Operations**: `search`, `list`, `get_metadata`, `get_content`, `list_folders`, `recent`, `by_type`, `large_files`
- **Smart Pagination**: Default 10 items to protect context window
- **Filters**: File type, date ranges, size, creator

#### 4. `file-parser` (NEW in v0.0.35)
Parse and extract text from SharePoint documents.
- **Supported Formats**: PDF, Excel, PowerPoint, HTML, RTF, text files
- **Input Methods**: 
  - File ID: `fileId: "01B65XAEES6VTGM5KFC5AYMZJX4RXAEMNN"`
  - File Path: `filePath: "/Documents/report.pdf"`
- **Operations**: `parse`, `summarize`, `metadata`

#### 5. `set-access-token`
Set Microsoft Graph access token for authentication.
- **Use Case**: Client-provided token authentication
- **Security**: Encrypted token storage

#### 6. `get-auth-status`
Check current authentication status and permissions.
- **Returns**: Token validity, expiration, granted scopes

#### 7. `add-graph-permission`
Request additional Graph API permissions interactively.
- **Use Case**: Dynamically add permissions when needed

#### 8. `health-check`
Monitor system health and API connectivity.
- **Checks**: Authentication, Graph API, rate limits, emergency controls

## 📦 Dependencies

### Core Dependencies

- **@modelcontextprotocol/sdk** (^1.7.0) - MCP protocol implementation
- **@microsoft/microsoft-graph-client** (^3.0.7) - Official Microsoft Graph SDK
- **@azure/identity** (^4.3.0) - Azure authentication library
- **zod** (^3.24.2) - Runtime type validation
- **jsonwebtoken** (^9.0.2) - JWT token parsing

### Document Parsing Dependencies

- **pdfjs-dist** (^5.4.149) - PDF document parsing (Apache-2.0)
- **xlsx** (^0.20.3) - Excel spreadsheet parsing (Apache-2.0)
- **yauzl** (^3.2.0) - ZIP file extraction for PowerPoint (MIT)
- **node-html-parser** (^7.0.1) - HTML document parsing (MIT)

### Runtime Requirements

- **Node.js**: Version 18.0.0 or higher
- **npm**: Version 8.0.0 or higher
- **Operating System**: Windows, macOS, or Linux

## 🛠️ Configuration

### Environment Variables

| Variable | Description | Required | Default |
|----------|-------------|----------|---------|
| `TENANT_ID` | Azure AD tenant ID | Yes* | "common" |
| `CLIENT_ID` | Application client ID | Yes* | Built-in app |
| `CLIENT_SECRET` | Client secret for app-only auth | Conditional | - |
| `USE_INTERACTIVE` | Enable interactive authentication | No | false |
| `USE_CERTIFICATE` | Enable certificate authentication | No | false |
| `CERTIFICATE_PATH` | Path to PEM certificate | Conditional | - |
| `CERTIFICATE_PASSWORD` | Certificate password if encrypted | No | - |
| `USE_CLIENT_TOKEN` | Enable token-based authentication | No | false |
| `STRICT_PERMISSION_MODE` | Enforce strict permission checking | No | false |
| `ENABLE_LOGGING` | Enable file logging | No | false |
| `ENABLE_AUDIT_LOG` | Enable audit logging for compliance | No | false |
| `LOG_LEVEL` | Set log level (ERROR, WARN, INFO, DEBUG) | No | ERROR |
| `LOG_DIR` | Directory for log files | No | ./logs |
| `RATE_LIMIT_MAX` | Max requests per window | No | 100 |
| `RATE_LIMIT_WINDOW_MS` | Rate limit time window (ms) | No | 60000 |
| `NODE_ENV` | Environment (development/production) | No | development |
| `ENABLE_TOKEN_CACHE` | Enable encrypted token caching | No | true |
| `TOKEN_CACHE_DIR` | Directory for token cache | No | OS temp dir |
| `CACHE_ENCRYPTION_SECRET` | Additional entropy for cache encryption | No | Auto-generated |

*Required unless using interactive mode with defaults

### Logging & Security Configuration

Configure logging and security settings to monitor operations, enforce permissions, and control API usage rates.

#### Example Configuration

```json
{
  "sharepoint-mcp": {
    "command": "npx",
    "args": ["-y", "@iimransarwar/sharepoint-mcp"],
    "env": {
      // Logging Configuration
      "ENABLE_LOGGING": "true",           // Enable detailed logging
      "LOG_LEVEL": "INFO",                // Log verbosity level
      "LOG_DIR": "/path/to/logs",         // Where to store log files
      "ENABLE_AUDIT_LOG": "true",         // Track sensitive operations
      
      // Security & Rate Limiting
      "STRICT_PERMISSION_MODE": "true",   // Enforce permission validation
      "RATE_LIMIT_MAX": "500",            // Max requests per window
      "RATE_LIMIT_WINDOW_MS": "60000",    // Time window (1 minute)
      
      // Your authentication config...
      "TENANT_ID": "your-tenant-id",
      "CLIENT_ID": "your-client-id",
      "CLIENT_SECRET": "your-secret"
    }
  }
}
```

#### Configuration Details

**Logging Settings:**
- **`ENABLE_LOGGING`**: When `true`, writes detailed logs to files for debugging and monitoring
  - Captures API calls, authentication events, errors, and system operations
  - Essential for troubleshooting production issues
  
- **`LOG_LEVEL`**: Controls the verbosity of logs
  - `ERROR`: Only critical errors
  - `WARN`: Warnings and errors
  - `INFO`: General information, API calls, and operations (recommended)
  - `DEBUG`: Detailed debugging information including data payloads
  
- **`LOG_DIR`**: Directory where log files are stored
  - Creates dated log files: `sharepoint-mcp-2025-09-09.log`
  - Ensure the directory exists and has write permissions
  - Default: `./logs` in the current working directory

- **`ENABLE_AUDIT_LOG`**: When `true`, creates separate audit logs for compliance
  - Tracks all write operations (POST, PUT, PATCH, DELETE)
  - Records who performed what action and when
  - Essential for security compliance and forensics
  - Stored as: `audit-2025-09-09.log`

**Security Settings:**
- **`STRICT_PERMISSION_MODE`**: When `true`, enforces scope validation
  - Validates that the token has required permissions for each operation
  - Blocks operations if proper scopes are missing
  - Recommended for production to prevent unauthorized access
  - When `false`, only logs warnings (use for development only)

**Rate Limiting:**
- **`RATE_LIMIT_MAX`**: Maximum number of requests allowed per time window
  - Default: 100 requests
  - Increase for high-volume operations
  - Prevents API abuse and protects against runaway scripts
  
- **`RATE_LIMIT_WINDOW_MS`**: Time window for rate limiting in milliseconds
  - Default: 60000 (1 minute)
  - Works with `RATE_LIMIT_MAX` to define requests per minute
  - Example: `500` requests per `60000`ms = 500 requests/minute

## 🔒 Security Features

### JWT Token Validation (v0.0.18+)

The server implements comprehensive JWT validation to ensure only legitimate Azure AD tokens are accepted:

- **Cryptographic Signature Verification**: All tokens are verified against Microsoft's RSA public keys
- **JWKS Key Rotation**: Automatically fetches and caches latest signing keys from Microsoft
- **Issuer Validation**: Only accepts tokens from configured Azure AD tenant
- **Audience Validation**: Ensures tokens are intended for your application
- **Expiration Checking**: Automatic rejection of expired tokens
- **Claims Validation**: Verifies presence of required token claims

### Additional Security Features

- **Rate Limiting**: Configurable request throttling to prevent abuse
- **Audit Logging**: Comprehensive logging of all sensitive operations
- **Permission Validation**: Scope-based access control for Graph API operations
- **Encrypted Token Cache**: AES-256-GCM encryption for cached tokens
- **Sensitive Data Sanitization**: Automatic redaction of secrets in logs

#### Production Configuration Example

```bash
# Recommended production settings
NODE_ENV=production
ENABLE_LOGGING=true
LOG_LEVEL=INFO
LOG_DIR=/var/log/sharepoint-mcp
ENABLE_AUDIT_LOG=true
STRICT_PERMISSION_MODE=true
RATE_LIMIT_MAX=100  # Lower for production
RATE_LIMIT_WINDOW_MS=60000
ENABLE_TOKEN_CACHE=true
# NEVER use interactive auth in production
USE_INTERACTIVE=false
```

#### Viewing Logs

```bash
# Watch logs in real-time
tail -f /path/to/logs/sharepoint-mcp-*.log

# View audit logs
tail -f /path/to/logs/audit-*.log

# Search for errors
grep ERROR /path/to/logs/sharepoint-mcp-*.log

# Monitor specific operations
grep "microsoft-graph tool" /path/to/logs/sharepoint-mcp-*.log
```

## 🔧 Troubleshooting

### Common Issues

#### 1. "Permission denied" Errors

**Problem**: Getting permission errors when trying to access resources.

**Solution**: 
- For **client credentials**: Ensure you've added Application permissions (not Delegated) and granted admin consent
- For **interactive auth**: Check that your user account has the necessary permissions
- Enable `STRICT_PERMISSION_MODE=false` for development (not recommended for production)

#### 2. Browser Opens on Every Start (Interactive Mode)

**Problem**: Browser authentication popup appears every time Claude restarts.

**Solution**: 
- The server now includes encrypted token caching that persists tokens across restarts
- Tokens are automatically cached and reused when valid
- For permanent authentication, switch to client credentials or certificate authentication

#### 3. "Rate limit exceeded" Errors

**Problem**: Too many API calls triggering rate limits.

**Solution**: 
- Increase `RATE_LIMIT_MAX` environment variable
- Add delays between bulk operations
- Use pagination (`fetchAll: false`) for large datasets

#### 4. "Failed to acquire token" Errors

**Problem**: Authentication is failing.

**Solutions**:
- Verify your tenant ID and client ID are correct
- Check that the client secret hasn't expired
- Ensure the certificate file exists and has correct permissions
- For interactive mode, check your browser allows popups

### Permission Reference

#### Delegated vs Application Permissions

| Type | When to Use | Example Scenario |
|------|-------------|------------------|
| **Delegated** | User is signed in (interactive) | "Show me my emails" |
| **Application** | No user context (client credentials) | "List all users in the organization" |

#### Common Permission Scopes

**For User Management**:
- `User.Read.All` - Read all user profiles
- `User.ReadWrite.All` - Create and modify users

**For SharePoint**:
- `Sites.Read.All` - Read all SharePoint sites
- `Sites.ReadWrite.All` - Modify SharePoint content
- `Files.Read.All` - Read all files

**For Microsoft Teams**:
- `Team.ReadBasic.All` - Read team information
- `Channel.ReadBasic.All` - Read channel information

**For Email**:
- `Mail.Read` - Read emails
- `Mail.Send` - Send emails

## 🔒 Security

This MCP server includes enterprise-grade security features:

- **Token Sanitization**: All sensitive data is automatically redacted from logs
- **Rate Limiting**: Prevents API abuse with configurable limits
- **Audit Logging**: Tracks all sensitive operations for compliance
- **Permission Validation**: Enforces scope-based access control
- **Secure Credential Handling**: Supports certificate-based authentication
- **Encrypted Token Cache**: AES-256-GCM encryption for cached tokens with machine-specific keys

For detailed security configuration, see [SECURITY.md](./SECURITY.md).

## 📝 Usage Examples

### Document Parsing (NEW)
```
"Parse the PDF file with ID 01B65XAEES6VTGM5KFC5AYMZJX4RXAEMNN from the Intranet site"
"Extract text from /Documents/Reports/Q4-2024.pdf in SharePoint"
"Summarize the Excel spreadsheet Budget.xlsx from the Finance site"
```

### SharePoint File Operations
```
"List PDF files in the Intranet site, show only 10 results"
"Search for files modified in the last week in HR Portal"
"Find all Excel files larger than 5MB in the Finance site"
```

### Query SharePoint Sites
```
"Show me all SharePoint sites in my tenant"
"Find sites that contain 'project' in their name"
"List my recently accessed SharePoint sites"
```

### Manage Users
```
"Create a new user with email john.doe@company.com"
"List all users in the Sales department"
```

### Access Teams Information
```
"Show me all Teams I'm a member of"
"List channels in the Marketing team"
```

### Azure Resource Management
```
"List all resource groups in my subscription"
"Show me the cost analysis for last month"
```

## 🤝 Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

## 📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

## 🆘 Support

For issues, questions, or feature requests:
- Reach out to 1@1m.au
---


**Note**: This MCP (Model Context Protocol) server is an **independent project** and is **not officially affiliated with, endorsed by, or sponsored by Microsoft Corporation**. Microsoft Graph, SharePoint, Azure, and all related trademarks are the property of Microsoft Corporation.

## Terms of Use

By using this tool, you acknowledge and agree to the following:

### Your Responsibility
- **YOU** are solely responsible for how you use this tool
- **YOU** must ensure compliance with all applicable laws, regulations, and terms of service
- **YOU** must have proper authorization to access any systems, data, or resources
- **YOU** are responsible for any consequences resulting from your use of this tool

### No Liability
The developer(s) of this tool:
- Accept **NO responsibility** for any illegal, unauthorized, or improper use
- Are **NOT liable** for any damages, losses, or consequences arising from your use
- Provide this tool "AS IS" without any warranties, express or implied
- Make **NO guarantees** about the tool's functionality, reliability, or suitability for any purpose

### Prohibited Use
This tool must **NOT** be used for:
- Illegal activities of any kind
- Unauthorized access to systems or data
- Violating Microsoft's Terms of Service or any other service agreements
- Any activity that could harm individuals, organizations, or systems

### Data and Privacy
- The developer(s) do **NOT** collect, store, or have access to your data
- **YOU** are responsible for protecting any credentials, tokens, or sensitive information
- **YOU** must comply with all applicable data protection and privacy laws

## USE AT YOUR OWN RISK

By using this tool, you accept full responsibility for your actions and agree to indemnify and hold harmless the developer(s) from any and all claims, damages, or liabilities arising from your use.

**If you do not agree with these terms, DO NOT use this tool.**