mcp-server-development-protocol.mdx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. ---
  2. title: "MCP Server Development Protocol"
  3. description: "This protocol is designed to streamline the development process of building MCP servers with Cline."
  4. ---
  5. > **Build and share your MCP servers with the world.** Once you've created a great MCP server, submit it to the [Cline MCP Marketplace](https://github.com/cline/mcp-marketplace) to make it discoverable and one-click installable by thousands of developers.
  6. ## What Are MCP Servers?
  7. Model Context Protocol (MCP) servers extend AI assistants like Cline by giving them the ability to:
  8. - Access external APIs and services
  9. - Retrieve real-time data
  10. - Control applications and local systems
  11. - Perform actions beyond what text prompts alone can achieve
  12. Without MCP, AI assistants are powerful but isolated. With MCP, they gain the ability to interact with virtually any digital system.
  13. ## The Development Protocol
  14. The heart of effective MCP server development is following a structured protocol. This protocol is implemented through a `.clinerules` file that lives at the **root** of your MCP working directory (/Users/your-name/Documents/Cline/MCP).
  15. ### Using `.clinerules` Files
  16. A `.clinerules` file is a special configuration that Cline reads automatically when working in the directory where it's placed. These files:
  17. - Configure Cline's behavior and enforce best practices
  18. - Switch Cline into a specialized MCP development mode
  19. - Provide a step-by-step protocol for building servers
  20. - Implement safety measures like preventing premature completion
  21. - Guide you through planning, implementation, and testing phases
  22. Here's the complete MCP Server Development Protocol that should be placed in your `.clinerules` file:
  23. ````markdown
  24. # MCP Server Development Protocol
  25. CRITICAL: DO NOT USE attempt_completion BEFORE TESTING
  26. ## Step 1: Planning (PLAN MODE)
  27. - What problem does this tool solve?
  28. - What API/service will it use?
  29. - What are the authentication requirements?
  30. □ Standard API key
  31. □ OAuth (requires separate setup script)
  32. □ Other credentials
  33. ## Step 2: Implementation (ACT MODE)
  34. 1. Bootstrap
  35. - For web services, JavaScript integration, or Node.js environments:
  36. ```bash
  37. npx @modelcontextprotocol/create-server my-server
  38. cd my-server
  39. npm install
  40. ```
  41. - For data science, ML workflows, or Python environments:
  42. ```bash
  43. pip install mcp
  44. # Or with uv (recommended)
  45. uv add "mcp[cli]"
  46. ```
  47. 2. Core Implementation
  48. - Use MCP SDK
  49. - Implement comprehensive logging
  50. - TypeScript (for web/JS projects):
  51. ```typescript
  52. console.error("[Setup] Initializing server...")
  53. console.error("[API] Request to endpoint:", endpoint)
  54. console.error("[Error] Failed with:", error)
  55. ```
  56. - Python (for data science/ML projects):
  57. ```python
  58. import logging
  59. logging.error('[Setup] Initializing server...')
  60. logging.error(f'[API] Request to endpoint: {endpoint}')
  61. logging.error(f'[Error] Failed with: {str(error)}')
  62. ```
  63. - Add type definitions
  64. - Handle errors with context
  65. - Implement rate limiting if needed
  66. 3. Configuration
  67. - Get credentials from user if needed
  68. - Add to MCP settings:
  69. - For TypeScript projects:
  70. ```json
  71. {
  72. "mcpServers": {
  73. "my-server": {
  74. "command": "node",
  75. "args": ["path/to/build/index.js"],
  76. "env": {
  77. "API_KEY": "key"
  78. },
  79. "disabled": false,
  80. "autoApprove": []
  81. }
  82. }
  83. }
  84. ```
  85. - For Python projects:
  86. ```bash
  87. # Directly with command line
  88. mcp install server.py -v API_KEY=key
  89. # Or in settings.json
  90. {
  91. "mcpServers": {
  92. "my-server": {
  93. "command": "python",
  94. "args": ["server.py"],
  95. "env": {
  96. "API_KEY": "key"
  97. },
  98. "disabled": false,
  99. "autoApprove": []
  100. }
  101. }
  102. }
  103. ```
  104. ## Step 3: Testing (BLOCKER ⛔️)
  105. <thinking>
  106. BEFORE using attempt_completion, I MUST verify:
  107. □ Have I tested EVERY tool?
  108. □ Have I confirmed success from the user for each test?
  109. □ Have I documented the test results?
  110. If ANY answer is "no", I MUST NOT use attempt_completion.
  111. </thinking>
  112. 1. Test Each Tool (REQUIRED)
  113. □ Test each tool with valid inputs
  114. □ Verify output format is correct
  115. DO NOT PROCEED UNTIL ALL TOOLS TESTED
  116. ## Step 4: Completion
  117. ❗ STOP AND VERIFY:
  118. □ Every tool has been tested with valid inputs
  119. □ Output format is correct for each tool
  120. Only after ALL tools have been tested can attempt_completion be used.
  121. ## Key Requirements
  122. - ✓ Must use MCP SDK
  123. - ✓ Must have comprehensive logging
  124. - ✓ Must test each tool individually
  125. - ✓ Must handle errors gracefully
  126. - NEVER skip testing before completion
  127. ````
  128. When this `.clinerules` file is present in your working directory, Cline will:
  129. 1. Start in **PLAN MODE** to design your server before implementation
  130. 2. Enforce proper implementation patterns in **ACT MODE**
  131. 3. Require testing of all tools before allowing completion
  132. 4. Guide you through the entire development lifecycle
  133. ## Getting Started
  134. Creating an MCP server requires just a few simple steps to get started:
  135. ### 1. Create a `.clinerules` file (IMPORTANT)
  136. First, add a `.clinerules` file to the root of your MCP working directory using the protocol above. This file configures Cline to use the MCP development protocol when working in this folder.
  137. ### 2. Start a Chat with a Clear Description
  138. Begin your Cline chat by clearly describing what you want to build. Be specific about:
  139. - The purpose of your MCP server
  140. - Which API or service you want to integrate with
  141. - Any specific tools or features you need
  142. For example:
  143. ```plaintext
  144. I want to build an MCP server for the AlphaAdvantage financial API.
  145. It should allow me to get real-time stock data, perform technical
  146. analysis, and retrieve company financial information.
  147. ```
  148. ### 3. Work Through the Protocol
  149. Cline will automatically start in PLAN MODE, guiding you through the planning process:
  150. - Discussing the problem scope
  151. - Reviewing API documentation
  152. - Planning authentication methods
  153. - Designing tool interfaces
  154. When ready, switch to ACT MODE using the toggle at the bottom of the chat to begin implementation.
  155. ### 4. Provide API Documentation Early
  156. One of the most effective ways to help Cline build your MCP server is to share official API documentation right at the start:
  157. ```plaintext
  158. Here's the API documentation for the service:
  159. [Paste API documentation here]
  160. ```
  161. Providing comprehensive API details (endpoints, authentication, data structures) significantly improves Cline's ability to implement an effective MCP server.
  162. ## Understanding the Two Modes
  163. ### PLAN MODE
  164. In this collaborative phase, you work with Cline to design your MCP server:
  165. - Define the problem scope
  166. - Choose appropriate APIs
  167. - Plan authentication methods
  168. - Design the tool interfaces
  169. - Determine data formats
  170. ### ACT MODE
  171. Once planning is complete, Cline helps implement the server:
  172. - Set up the project structure
  173. - Write the implementation code
  174. - Configure settings
  175. - Test each component thoroughly
  176. - Finalize documentation
  177. ## Case Study: AlphaAdvantage Stock Analysis Server
  178. Let's walk through the development process of our AlphaAdvantage MCP server, which provides stock data analysis and reporting capabilities.
  179. ### Planning Phase
  180. <Frame>
  181. <img
  182. src="https://storage.googleapis.com/cline_public_images/docs/assets/planning-phase.gif"
  183. alt="Planning phase demonstration"
  184. />
  185. </Frame>
  186. During the planning phase, we:
  187. 1. **Defined the problem**: Users need access to financial data, stock analysis, and market insights directly through their AI assistant
  188. 2. **Selected the API**: AlphaAdvantage API for financial market data
  189. - Standard API key authentication
  190. - Rate limits of 5 requests per minute (free tier)
  191. - Various endpoints for different financial data types
  192. 3. **Designed the tools needed**:
  193. - Stock overview information (current price, company details)
  194. - Technical analysis with indicators (RSI, MACD, etc.)
  195. - Fundamental analysis (financial statements, ratios)
  196. - Earnings report data
  197. - News and sentiment analysis
  198. 4. **Planned data formatting**:
  199. - Clean, well-formatted markdown output
  200. - Tables for structured data
  201. - Visual indicators (↑/↓) for trends
  202. - Proper formatting of financial numbers
  203. ### Implementation
  204. <Frame>
  205. <img
  206. src="https://storage.googleapis.com/cline_public_images/docs/assets/building-mcp-plugin.gif"
  207. alt="Building MCP plugin demonstration"
  208. />
  209. </Frame>
  210. We began by bootstrapping the project:
  211. ```bash
  212. npx @modelcontextprotocol/create-server alphaadvantage-mcp
  213. cd alphaadvantage-mcp
  214. npm install axios node-cache
  215. ```
  216. Next, we structured our project with:
  217. ```plaintext
  218. src/
  219. ├── api/
  220. │ └── alphaAdvantageClient.ts # API client with rate limiting & caching
  221. ├── formatters/
  222. │ └── markdownFormatter.ts # Output formatters for clean markdown
  223. └── index.ts # Main MCP server implementation
  224. ```
  225. #### API Client Implementation
  226. The API client implementation included:
  227. - **Rate limiting**: Enforcing the 5 requests per minute limit
  228. - **Caching**: Reducing API calls with strategic caching
  229. - **Error handling**: Robust error detection and reporting
  230. - **Typed interfaces**: Clear TypeScript types for all data
  231. Key implementation details:
  232. ```typescript
  233. /**
  234. * Manage rate limiting based on free tier (5 calls per minute)
  235. */
  236. private async enforceRateLimit() {
  237. if (this.requestsThisMinute >= 5) {
  238. console.error("[Rate Limit] Rate limit reached. Waiting for next minute...");
  239. return new Promise<void>((resolve) => {
  240. const remainingMs = 60 * 1000 - (Date.now() % (60 * 1000));
  241. setTimeout(resolve, remainingMs + 100); // Add 100ms buffer
  242. });
  243. }
  244. this.requestsThisMinute++;
  245. return Promise.resolve();
  246. }
  247. ```
  248. #### Markdown Formatting
  249. We implemented formatters to display financial data beautifully:
  250. ```typescript
  251. /**
  252. * Format company overview into markdown
  253. */
  254. export function formatStockOverview(overviewData: any, quoteData: any): string {
  255. // Extract data
  256. const overview = overviewData
  257. const quote = quoteData["Global Quote"]
  258. // Calculate price change
  259. const currentPrice = parseFloat(quote["05. price"] || "0")
  260. const priceChange = parseFloat(quote["09. change"] || "0")
  261. const changePercent = parseFloat(quote["10. change percent"]?.replace("%", "") || "0")
  262. // Format markdown
  263. let markdown = `# ${overview.Symbol} (${overview.Name}) - ${formatCurrency(currentPrice)} ${addTrendIndicator(priceChange)}${changePercent > 0 ? "+" : ""}${changePercent.toFixed(2)}%\n\n`
  264. // Add more details...
  265. return markdown
  266. }
  267. ```
  268. #### Tool Implementation
  269. We defined five tools with clear interfaces:
  270. ```typescript
  271. server.setRequestHandler(ListToolsRequestSchema, async () => {
  272. console.error("[Setup] Listing available tools")
  273. return {
  274. tools: [
  275. {
  276. name: "get_stock_overview",
  277. description: "Get basic company info and current quote for a stock symbol",
  278. inputSchema: {
  279. type: "object",
  280. properties: {
  281. symbol: {
  282. type: "string",
  283. description: "Stock symbol (e.g., 'AAPL')",
  284. },
  285. market: {
  286. type: "string",
  287. description: "Optional market (e.g., 'US')",
  288. default: "US",
  289. },
  290. },
  291. required: ["symbol"],
  292. },
  293. },
  294. // Additional tools defined here...
  295. ],
  296. }
  297. })
  298. ```
  299. Each tool's handler included:
  300. - Input validation
  301. - API client calls with error handling
  302. - Markdown formatting of responses
  303. - Comprehensive logging
  304. ### Testing Phase
  305. This critical phase involved systematically testing each tool:
  306. 1. First, we configured the MCP server in the settings:
  307. ```json
  308. {
  309. "mcpServers": {
  310. "alphaadvantage-mcp": {
  311. "command": "node",
  312. "args": ["/path/to/alphaadvantage-mcp/build/index.js"],
  313. "env": {
  314. "ALPHAVANTAGE_API_KEY": "YOUR_API_KEY"
  315. },
  316. "disabled": false,
  317. "autoApprove": []
  318. }
  319. }
  320. }
  321. ```
  322. 2. Then we tested each tool individually:
  323. - **get_stock_overview**: Retrieved AAPL stock overview information
  324. ```markdown
  325. # AAPL (Apple Inc) - $241.84 ↑+1.91%
  326. **Sector:** TECHNOLOGY
  327. **Industry:** ELECTRONIC COMPUTERS
  328. **Market Cap:** 3.63T
  329. **P/E Ratio:** 38.26
  330. ...
  331. ```
  332. - **get_technical_analysis**: Obtained price action and RSI data
  333. ```markdown
  334. # Technical Analysis: AAPL
  335. ## Daily Price Action
  336. Current Price: $241.84 (↑$4.54, +1.91%)
  337. ### Recent Daily Prices
  338. | Date | Open | High | Low | Close | Volume |
  339. | ---------- | ------- | ------- | ------- | ------- | ------ |
  340. | 2025-02-28 | $236.95 | $242.09 | $230.20 | $241.84 | 56.83M |
  341. ...
  342. ```
  343. - **get_earnings_report**: Retrieved MSFT earnings history and formatted report
  344. ```markdown
  345. # Earnings Report: MSFT (Microsoft Corporation)
  346. **Sector:** TECHNOLOGY
  347. **Industry:** SERVICES-PREPACKAGED SOFTWARE
  348. **Current EPS:** $12.43
  349. ## Recent Quarterly Earnings
  350. | Quarter | Date | EPS Estimate | EPS Actual | Surprise % |
  351. | ---------- | ---------- | ------------ | ---------- | ---------- |
  352. | 2024-12-31 | 2025-01-29 | $3.11 | $3.23 | ↑4.01% |
  353. ...
  354. ```
  355. ### Challenges and Solutions
  356. During development, we encountered several challenges:
  357. 1. **API Rate Limiting**:
  358. - **Challenge**: Free tier limited to 5 calls per minute
  359. - **Solution**: Implemented queuing, enforced rate limits, and added comprehensive caching
  360. 2. **Data Formatting**:
  361. - **Challenge**: Raw API data not user-friendly
  362. - **Solution**: Created formatting utilities for consistent display of financial data
  363. 3. **Timeout Issues**:
  364. - **Challenge**: Complex tools making multiple API calls could timeout
  365. - **Solution**: Suggested breaking complex tools into smaller pieces, optimizing caching
  366. ### Lessons Learned
  367. Our AlphaAdvantage implementation taught us several key lessons:
  368. 1. **Plan for API Limits**: Understand and design around API rate limits from the beginning
  369. 2. **Cache Strategically**: Identify high-value caching opportunities to improve performance
  370. 3. **Format for Readability**: Invest in good data formatting for improved user experience
  371. 4. **Test Every Path**: Test all tools individually before completion
  372. 5. **Handle API Complexity**: For APIs requiring multiple calls, design tools with simpler scopes
  373. ## Core Implementation Best Practices
  374. ### Comprehensive Logging
  375. Effective logging is essential for debugging MCP servers:
  376. ```typescript
  377. // Start-up logging
  378. console.error("[Setup] Initializing AlphaAdvantage MCP server...")
  379. // API request logging
  380. console.error(`[API] Getting stock overview for ${symbol}`)
  381. // Error handling with context
  382. console.error(`[Error] Tool execution failed: ${error.message}`)
  383. // Cache operations
  384. console.error(`[Cache] Using cached data for: ${cacheKey}`)
  385. ```
  386. ### Strong Typing
  387. Type definitions prevent errors and improve maintainability:
  388. ```typescript
  389. export interface AlphaAdvantageConfig {
  390. apiKey: string
  391. cacheTTL?: Partial<typeof DEFAULT_CACHE_TTL>
  392. baseURL?: string
  393. }
  394. /**
  395. * Validate that a stock symbol is provided and looks valid
  396. */
  397. function validateSymbol(symbol: unknown): asserts symbol is string {
  398. if (typeof symbol !== "string" || symbol.trim() === "") {
  399. throw new McpError(ErrorCode.InvalidParams, "A valid stock symbol is required")
  400. }
  401. // Basic symbol validation (letters, numbers, dots)
  402. const symbolRegex = /^[A-Za-z0-9.]+$/
  403. if (!symbolRegex.test(symbol)) {
  404. throw new McpError(ErrorCode.InvalidParams, `Invalid stock symbol: ${symbol}`)
  405. }
  406. }
  407. ```
  408. ### Intelligent Caching
  409. Reduce API calls and improve performance:
  410. ```typescript
  411. // Default cache TTL in seconds
  412. const DEFAULT_CACHE_TTL = {
  413. STOCK_OVERVIEW: 60 * 60, // 1 hour
  414. TECHNICAL_ANALYSIS: 60 * 30, // 30 minutes
  415. FUNDAMENTAL_ANALYSIS: 60 * 60 * 24, // 24 hours
  416. EARNINGS_REPORT: 60 * 60 * 24, // 24 hours
  417. NEWS: 60 * 15, // 15 minutes
  418. }
  419. // Check cache first
  420. const cachedData = this.cache.get<T>(cacheKey)
  421. if (cachedData) {
  422. console.error(`[Cache] Using cached data for: ${cacheKey}`)
  423. return cachedData
  424. }
  425. // Cache successful responses
  426. this.cache.set(cacheKey, response.data, cacheTTL)
  427. ```
  428. ### Graceful Error Handling
  429. Implement robust error handling that maintains a good user experience:
  430. ```typescript
  431. try {
  432. switch (request.params.name) {
  433. case "get_stock_overview": {
  434. // Implementation...
  435. }
  436. // Other cases...
  437. default:
  438. throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`)
  439. }
  440. } catch (error) {
  441. console.error(`[Error] Tool execution failed: ${error instanceof Error ? error.message : String(error)}`)
  442. if (error instanceof McpError) {
  443. throw error
  444. }
  445. return {
  446. content: [
  447. {
  448. type: "text",
  449. text: `Error: ${error instanceof Error ? error.message : String(error)}`,
  450. },
  451. ],
  452. isError: true,
  453. }
  454. }
  455. ```
  456. ## MCP Resources
  457. Resources let your MCP servers expose data to Cline without executing code. They're perfect for providing context like files, API responses, or database records that Cline can reference during conversations.
  458. ### Adding Resources to Your MCP Server
  459. 1. **Define the resources** your server will expose:
  460. ```typescript
  461. server.setRequestHandler(ListResourcesRequestSchema, async () => {
  462. return {
  463. resources: [
  464. {
  465. uri: "file:///project/readme.md",
  466. name: "Project README",
  467. mimeType: "text/markdown",
  468. },
  469. ],
  470. }
  471. })
  472. ```
  473. 2. **Implement read handlers** to deliver the content:
  474. ```typescript
  475. server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  476. if (request.params.uri === "file:///project/readme.md") {
  477. const content = await fs.promises.readFile("/path/to/readme.md", "utf-8")
  478. return {
  479. contents: [
  480. {
  481. uri: request.params.uri,
  482. mimeType: "text/markdown",
  483. text: content,
  484. },
  485. ],
  486. }
  487. }
  488. throw new Error("Resource not found")
  489. })
  490. ```
  491. Resources make your MCP servers more context-aware, allowing Cline to access specific information without requiring you to copy/paste. For more information, refer to the [official documentation](https://modelcontextprotocol.io/docs/concepts/resources).
  492. ## Common Challenges and Solutions
  493. ### API Authentication Complexities
  494. **Challenge**: APIs often have different authentication methods.
  495. **Solution**:
  496. - For API keys, use environment variables in the MCP configuration
  497. - For OAuth, create a separate script to obtain refresh tokens
  498. - Store sensitive tokens securely
  499. ```typescript
  500. // Authenticate using API key from environment
  501. const API_KEY = process.env.ALPHAVANTAGE_API_KEY
  502. if (!API_KEY) {
  503. console.error("[Error] Missing ALPHAVANTAGE_API_KEY environment variable")
  504. process.exit(1)
  505. }
  506. // Initialize API client
  507. const apiClient = new AlphaAdvantageClient({
  508. apiKey: API_KEY,
  509. })
  510. ```
  511. ### Missing or Limited API Features
  512. **Challenge**: APIs may not provide all the functionality you need.
  513. **Solution**:
  514. - Implement fallbacks using available endpoints
  515. - Create simulated functionality where necessary
  516. - Transform API data to match your needs
  517. ### API Rate Limiting
  518. **Challenge**: Most APIs have rate limits that can cause failures.
  519. **Solution**:
  520. - Implement proper rate limiting
  521. - Add intelligent caching
  522. - Provide graceful degradation
  523. - Add transparent errors about rate limits
  524. ```typescript
  525. if (this.requestsThisMinute >= 5) {
  526. console.error("[Rate Limit] Rate limit reached. Waiting for next minute...")
  527. return new Promise<void>((resolve) => {
  528. const remainingMs = 60 * 1000 - (Date.now() % (60 * 1000))
  529. setTimeout(resolve, remainingMs + 100) // Add 100ms buffer
  530. })
  531. }
  532. ```
  533. ## Additional Resources
  534. - [MCP Protocol Documentation](https://github.com/modelcontextprotocol/mcp)
  535. - [MCP SDK Documentation](https://github.com/modelcontextprotocol/sdk-js)
  536. - [MCP Server Examples](https://github.com/modelcontextprotocol/servers)