SharePoint MCP: The .NET MCP Server with Graph API & Semantic Kernel
Okay, I understand. You want to create an **MCP (Message Center Provider) server** to access **SharePoint Online**. However, there's a potential misunderstanding here. "MCP server" isn't a standard term in the context of SharePoint Online development. It sounds like you're aiming to build a custom application or service that interacts with SharePoint Online data, possibly to receive and process notifications or updates. Therefore, I'll provide you with a general outline and explanation of how to build a service that can access SharePoint Online data, including how to handle notifications and changes. This will involve using the Microsoft Graph API and/or the SharePoint REST API. Here's a breakdown of the steps and considerations, along with the Chinese translation of key terms: **1. Understanding the Goal (理解目标)** * **English:** You want to create a service that can access and potentially react to changes in SharePoint Online. This might involve: * Retrieving data (lists, libraries, documents, etc.) * Monitoring for changes (new files, updated items, etc.) * Performing actions based on those changes (e.g., sending notifications, triggering workflows). * **Chinese:** 你想创建一个服务,可以访问并可能对 SharePoint Online 中的更改做出反应。 这可能涉及: * 检索数据(列表、库、文档等) * 监视更改(新文件、更新的项目等) * 根据这些更改执行操作(例如,发送通知、触发工作流)。 **2. Choosing an API (选择 API)** * **Microsoft Graph API (Microsoft Graph API):** This is the recommended approach for most new development. It provides a unified endpoint to access data across Microsoft 365, including SharePoint Online. It's generally easier to use and more feature-rich than the SharePoint REST API. * **SharePoint REST API (SharePoint REST API):** This is a more direct way to interact with SharePoint Online. It's useful if you need very specific control over SharePoint features. **3. Authentication and Authorization (身份验证和授权)** * **English:** Your service needs to authenticate with Azure Active Directory (Azure AD) to access SharePoint Online. You'll need to register an application in Azure AD and grant it the necessary permissions. There are two main authentication flows: * **Delegated Permissions (委派权限):** The application acts on behalf of a user. The user needs to grant consent to the application. * **Application Permissions (应用程序权限):** The application acts on its own behalf, without a user. This requires administrator consent. This is generally preferred for background services. * **Chinese:** 您的服务需要使用 Azure Active Directory (Azure AD) 进行身份验证才能访问 SharePoint Online。 您需要在 Azure AD 中注册一个应用程序,并授予它必要的权限。 有两种主要的身份验证流程: * **委派权限:** 应用程序代表用户行事。 用户需要授予应用程序同意。 * **应用程序权限:** 应用程序代表自己行事,无需用户。 这需要管理员同意。 这通常是后台服务的首选。 **4. Development Steps (开发步骤)** Here's a general outline of the development process, using the Microsoft Graph API as an example: * **Step 1: Register an Application in Azure AD (在 Azure AD 中注册应用程序)** * Go to the Azure portal (portal.azure.com). * Navigate to "Azure Active Directory" -> "App registrations". * Click "New registration". * Give your application a name (e.g., "SharePointDataService"). * Choose the appropriate account type (usually "Single tenant"). * Set the redirect URI (if needed; for a background service, this might not be necessary). * Click "Register". * Note the "Application (client) ID" and "Directory (tenant) ID". You'll need these later. * **Step 2: Grant API Permissions (授予 API 权限)** * In your Azure AD app registration, go to "API permissions". * Click "Add a permission". * Select "Microsoft Graph". * Choose "Application permissions" (for a background service). * Search for and select the necessary permissions. Common permissions include: * `Sites.Read.All` (Read SharePoint sites) * `Sites.ReadWrite.All` (Read and write SharePoint sites) * `Sites.Manage.All` (Full control of SharePoint sites) * `Files.Read.All` (Read all files) * `Files.ReadWrite.All` (Read and write all files) * Click "Add permissions". * **Important:** After adding application permissions, you need to grant admin consent. Click "Grant admin consent for [Your Tenant Name]". * **Step 3: Obtain an Access Token (获取访问令牌)** * You'll need to use a library like MSAL (Microsoft Authentication Library) to obtain an access token. The code will vary depending on your programming language. Here's a Python example using `msal`: ```python import msal # Replace with your actual values CLIENT_ID = "YOUR_CLIENT_ID" CLIENT_SECRET = "YOUR_CLIENT_SECRET" TENANT_ID = "YOUR_TENANT_ID" AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}" SCOPES = ["https://graph.microsoft.com/.default"] # Use .default for application permissions app = msal.ConfidentialClientApplication( CLIENT_ID, authority=AUTHORITY, client_credential=CLIENT_SECRET ) result = app.acquire_token_for_client(scopes=SCOPES) if "access_token" in result: access_token = result["access_token"] print("Access Token:", access_token) else: print(result.get("error_description", "No error information available")) ``` * **Chinese:** ```python import msal # 替换为您的实际值 CLIENT_ID = "YOUR_CLIENT_ID" CLIENT_SECRET = "YOUR_CLIENT_SECRET" TENANT_ID = "YOUR_TENANT_ID" AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}" SCOPES = ["https://graph.microsoft.com/.default"] # 使用 .default 作为应用程序权限 app = msal.ConfidentialClientApplication( CLIENT_ID, authority=AUTHORITY, client_credential=CLIENT_SECRET ) result = app.acquire_token_for_client(scopes=SCOPES) if "access_token" in result: access_token = result["access_token"] print("访问令牌:", access_token) else: print(result.get("error_description", "没有可用的错误信息")) ``` * **Step 4: Call the Microsoft Graph API (调用 Microsoft Graph API)** * Use the access token to make requests to the Microsoft Graph API. For example, to get a list of SharePoint sites: ```python import requests GRAPH_API_ENDPOINT = "https://graph.microsoft.com/v1.0/sites" headers = { "Authorization": f"Bearer {access_token}" } response = requests.get(GRAPH_API_ENDPOINT, headers=headers) if response.status_code == 200: sites = response.json() print("SharePoint Sites:", sites) else: print("Error:", response.status_code, response.text) ``` * **Chinese:** ```python import requests GRAPH_API_ENDPOINT = "https://graph.microsoft.com/v1.0/sites" headers = { "Authorization": f"Bearer {access_token}" } response = requests.get(GRAPH_API_ENDPOINT, headers=headers) if response.status_code == 200: sites = response.json() print("SharePoint 站点:", sites) else: print("错误:", response.status_code, response.text) ``` * **Step 5: Handle Changes and Notifications (处理更改和通知)** * **Microsoft Graph Change Notifications (Microsoft Graph 更改通知):** This is the recommended way to receive notifications about changes in SharePoint Online. You can subscribe to changes on specific resources (e.g., a list, a library, a file). When a change occurs, Microsoft Graph will send a notification to your service. You'll need to set up a webhook endpoint to receive these notifications. * **SharePoint Webhooks (SharePoint Webhooks):** An older method, but still supported. Similar to Microsoft Graph Change Notifications, but specific to SharePoint. * **Polling (轮询):** The least efficient method. Your service periodically checks for changes. Avoid this if possible. **5. Key Considerations (关键考虑因素)** * **Error Handling (错误处理):** Implement robust error handling to deal with API errors, authentication failures, and other issues. * **Rate Limiting (速率限制):** Be aware of Microsoft Graph API and SharePoint REST API rate limits. Implement retry logic and caching to avoid exceeding these limits. * **Security (安全):** Protect your client ID and client secret. Store them securely (e.g., using Azure Key Vault). * **Scalability (可扩展性):** Design your service to be scalable to handle a large number of requests and notifications. * **Permissions (权限):** Only request the minimum permissions required for your service to function. * **Monitoring (监控):** Implement monitoring to track the health and performance of your service. **Example: Setting up a Microsoft Graph Change Notification (示例:设置 Microsoft Graph 更改通知)** This is a simplified example. You'll need to adapt it to your specific requirements. 1. **Create a Webhook Endpoint (创建 Webhook 端点):** This is an HTTP endpoint that will receive notifications from Microsoft Graph. You'll need to make this endpoint publicly accessible (e.g., using Azure Functions, Azure App Service, or a similar service). 2. **Create a Subscription (创建订阅):** Use the Microsoft Graph API to create a subscription to the resource you want to monitor. For example, to subscribe to changes in a SharePoint list: ```python import requests import json GRAPH_API_ENDPOINT = "https://graph.microsoft.com/v1.0/subscriptions" WEBHOOK_URL = "YOUR_WEBHOOK_URL" # Replace with your webhook URL RESOURCE = "sites/{site-id}/lists/{list-id}/items" # Replace with your site and list IDs subscription_data = { "changeType": "created,updated,deleted", "notificationUrl": WEBHOOK_URL, "resource": RESOURCE, "expirationDateTime": "2024-12-31T23:59:00.0000000Z", # Adjust expiration date "clientState": "secretClientValue" # Optional, for validation } headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } response = requests.post(GRAPH_API_ENDPOINT, headers=headers, data=json.dumps(subscription_data)) if response.status_code == 201: subscription = response.json() print("Subscription created:", subscription) else: print("Error creating subscription:", response.status_code, response.text) ``` * **Chinese:** ```python import requests import json GRAPH_API_ENDPOINT = "https://graph.microsoft.com/v1.0/subscriptions" WEBHOOK_URL = "YOUR_WEBHOOK_URL" # 替换为您的 webhook URL RESOURCE = "sites/{site-id}/lists/{list-id}/items" # 替换为您的站点和列表 ID subscription_data = { "changeType": "created,updated,deleted", "notificationUrl": WEBHOOK_URL, "resource": RESOURCE, "expirationDateTime": "2024-12-31T23:59:00.0000000Z", # 调整过期日期 "clientState": "secretClientValue" # 可选,用于验证 } headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } response = requests.post(GRAPH_API_ENDPOINT, headers=headers, data=json.dumps(subscription_data)) if response.status_code == 201: subscription = response.json() print("订阅已创建:", subscription) else: print("创建订阅时出错:", response.status_code, response.text) ``` 3. **Handle the Notification (处理通知):** When a change occurs, Microsoft Graph will send a POST request to your webhook endpoint. Your endpoint needs to: * **Validate the request:** Verify the `clientState` (if you used it). * **Process the notification:** Extract the information about the change and take appropriate action. **Important Notes:** * This is a high-level overview. You'll need to consult the Microsoft Graph API documentation and SharePoint REST API documentation for detailed information. * The code examples are in Python, but you can use any programming language that supports HTTP requests. * Remember to replace the placeholder values (e.g., `YOUR_CLIENT_ID`, `YOUR_CLIENT_SECRET`, `YOUR_TENANT_ID`, `YOUR_WEBHOOK_URL`, `site-id`, `list-id`) with your actual values. * Consider using a framework like Flask or Django (for Python) to build your webhook endpoint. This comprehensive guide should help you get started with building a service to access SharePoint Online data and handle notifications. Remember to adapt the code and steps to your specific requirements. Good luck!
mhmd2015
README
SharePoint MCP:基于 Graph API 和 Semantic Kernel 的 .NET MCP 服务器
在现代企业中,安全高效地访问特定数据至关重要,尤其是在与 AI 功能集成时。想象一下,一个聊天机器人不仅可以进行智能对话,还可以直接从您组织的 SharePoint 站点获取相关文档或信息。本文概述了一种使用 .NET、Microsoft Graph API、Semantic Kernel 和 Gemini AI 实现此目标的模块化架构。
该项目由三个不同的模块组成:
- MCP 服务器(Semantic Kernel):我们 SharePoint 交互的大脑。
- SharePoint 连接器库:伸入 SharePoint Online 的双手。
- MCP 客户端(Gemini AI):面向用户的聊天界面。
让我们分解每个模块:
模块 1:.NET MCP 服务器(利用 Semantic Kernel)
此核心组件充当中央枢纽和 API 端点。我们使用 .NET 构建,并在此处集成 Semantic Kernel。虽然它可以是一个标准的 ASP.NET Core Web API,但使用 Semantic Kernel 允许我们将 SharePoint 交互定义为原生“技能”或“插件”。
通过客户端可以调用的 API 端点公开功能(如 SharePoint 搜索)。使用 .NET(例如,ASP.NET Core Web API)、Semantic Kernel SDK 编排对连接器库的调用。 关键功能:定义一个 API 路由(例如,/api/sharepoint/search),该路由接受搜索查询。此路由将调用我们连接器库中的函数。如果以后需要,使用 Semantic Kernel 可以轻松地将此函数集成到更复杂的 AI 推理流程中。
模块 2:SharePoint 连接器库(Graph API)
这个 .NET 库专门负责与 SharePoint Online 通信的细节。
目的:使用 Microsoft Graph 进行身份验证并执行特定的 SharePoint 操作,从搜索开始。 技术:.NET Standard 或 .NET Core 库,Microsoft.Graph SDK。 身份验证:使用客户端 ID 和客户端密钥(仅应用身份验证)。 设置:需要在 Azure Active Directory (Azure AD) 中注册一个应用程序,授予它必要的 Graph API 权限(例如,Sites.Read.All 或更细粒度的权限,具体取决于您的需求),并获得管理员同意。至关重要的是,安全地存储您的客户端密钥(例如,Azure Key Vault、.NET 用户机密)——永远不要对其进行硬编码! 关键功能:一个异步函数(例如,SearchSharePointAsync(string query)),它: 使用客户端 ID 和密钥获取 Microsoft Graph 的访问令牌。 构造一个 Graph API 请求到 SharePoint 搜索端点 (/search/query)。 使用 Microsoft.Graph SDK 发送请求。 解析响应并返回相关的搜索结果(例如,文档名称、链接、摘要)。
模块 3:MCP 客户端(Gemini AI)
这是您的用户与之交互的应用程序。它具有由 Gemini AI 提供支持的聊天界面。
目的:提供 AI 驱动的对话体验。检测与 SharePoint 相关的用户意图,并将这些任务委派给 MCP 服务器。 技术:任何客户端平台(.NET MAUI、Blazor、控制台应用程序等),Google AI Gemini SDK。 功能: 用户与 Gemini 驱动的界面聊天。 客户端应用程序(或可能是 Gemini 本身,具体取决于实现)分析对话。 当检测到与“SharePoint”(或特定文档类型、站点等)相关的关键字或意图时,客户端使用相关查询向 MCP 服务器的 API 端点(例如,/api/sharepoint/search)发出 HTTP 请求。 它从服务器接收搜索结果,并在聊天上下文中将其呈现给用户。 工作流程示例:
用户:“Hey Gemini,你能找到 SharePoint 上的 Q1 营销报告吗?” MCP 客户端:检测到“SharePoint”和“Q1 营销报告”。 MCP 客户端:将带有查询“Q1 营销报告”的 POST /api/sharepoint/search 发送到 MCP 服务器。 MCP 服务器:接收请求,在连接器库中调用 SearchSharePointAsync("Q1 营销报告")。 连接器库:使用客户端 ID/密钥通过 Graph API 进行身份验证,执行搜索 /search/query。 SharePoint Online:返回搜索结果。 连接器库:将格式化的结果返回给 MCP 服务器。 MCP 服务器:在 API 响应中将结果返回给 MCP 客户端。 MCP 客户端:在 Gemini 聊天界面中显示结果(例如,“我找到了这些文档:[链接 1],[链接 2]”)。 好处:
模块化设计:清晰的关注点分离使开发和维护更容易。 安全访问:仅应用身份验证确保对 SharePoint 数据的受控访问,而无需在后端进行用户模拟。 AI 集成:将对话式 AI 与企业数据检索无缝融合。 可扩展:轻松地将更多 SharePoint 功能(上传、列出文件等)添加到连接器库,并通过 MCP 服务器公开它们。
推荐服务器
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Claude Code MCP
一个实现了 Claude Code 作为模型上下文协议(Model Context Protocol, MCP)服务器的方案,它可以通过标准化的 MCP 接口来使用 Claude 的软件工程能力(代码生成、编辑、审查和文件操作)。
@kazuph/mcp-taskmanager
用于任务管理的模型上下文协议服务器。它允许 Claude Desktop(或任何 MCP 客户端)在基于队列的系统中管理和执行任务。
MCP Package Docs Server
促进大型语言模型高效访问和获取 Go、Python 和 NPM 包的结构化文档,通过多语言支持和性能优化来增强软件开发。
mermaid-mcp-server
一个模型上下文协议 (MCP) 服务器,用于将 Mermaid 图表转换为 PNG 图像。
Jira-Context-MCP
MCP 服务器向 AI 编码助手(如 Cursor)提供 Jira 工单信息。
Linear MCP Server
一个模型上下文协议(Model Context Protocol)服务器,它与 Linear 的问题跟踪系统集成,允许大型语言模型(LLM)通过自然语言交互来创建、更新、搜索和评论 Linear 问题。
Sequential Thinking MCP Server
这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。
Curri MCP Server
通过管理文本笔记、提供笔记创建工具以及使用结构化提示生成摘要,从而实现与 Curri API 的交互。