MCP Server Development Protocol
This protocol aims to optimize and simplify the MCP server development workflow when working with Sypha.
Create and distribute your MCP servers globally. After developing a high-quality MCP server, you can submit it to the Sypha MCP Marketplace, making it easily discoverable and installable via one-click for thousands of developers worldwide.
Understanding MCP Servers
Through Model Context Protocol (MCP) servers, AI assistants such as Sypha receive enhanced capabilities, enabling them to:
- Interface with external APIs and third-party services
- Obtain data in real-time
- Manage applications and local system operations
- Execute operations that transcend the limitations of text-based prompts
In the absence of MCP, AI assistants remain potent yet confined. MCP integration grants them the capability to interface with practically any digital ecosystem.
The Structured Development Protocol
Successful MCP server development centers on adhering to a well-defined protocol. Implementation occurs through a .sypharules file positioned at the root level of your MCP working directory (/Users/your-name/Documents/Sypha/MCP).
Working with .sypharules Files
A .sypharules file represents a specialized configuration automatically processed by Sypha when operating within its containing directory. These configuration files:
- Establish Sypha's operational behavior and maintain best practice standards
- Activate a dedicated MCP development mode within Sypha
- Present a methodical, step-by-step server construction protocol
- Incorporate protective mechanisms such as premature completion prevention
- Direct you through sequential planning, implementation, and testing stages
Below is the comprehensive MCP Server Development Protocol for inclusion in your .sypharules file:
# MCP Server Development Protocol
CRITICAL: DO NOT USE attempt_completion BEFORE TESTING
## Step 1: Planning (PLAN MODE)
- What problem does this tool solve?
- What API/service will it use?
- What are the authentication requirements?
□ Standard API key
□ OAuth (requires separate setup script)
□ Other credentials
## Step 2: Implementation (ACT MODE)
1. Bootstrap
- For web services, JavaScript integration, or Node.js environments:
```bash
npx @modelcontextprotocol/create-server my-server
cd my-server
npm install
```
- For data science, ML workflows, or Python environments:
```bash
pip install mcp
# Or with uv (recommended)
uv add "mcp[cli]"
```
2. Core Implementation
- Use MCP SDK
- Implement comprehensive logging
- TypeScript (for web/JS projects):
```typescript
console.error("[Setup] Initializing server...")
console.error("[API] Request to endpoint:", endpoint)
console.error("[Error] Failed with:", error)
```
- Python (for data science/ML projects):
```python
import logging
logging.error('[Setup] Initializing server...')
logging.error(f'[API] Request to endpoint: {endpoint}')
logging.error(f'[Error] Failed with: {str(error)}')
```
- Add type definitions
- Handle errors with context
- Implement rate limiting if needed
3. Configuration
- Get credentials from user if needed
- Add to MCP settings:
- For TypeScript projects:
```json
{
"mcpServers": {
"my-server": {
"command": "node",
"args": ["path/to/build/index.js"],
"env": {
"API_KEY": "key"
},
"disabled": false,
"autoApprove": []
}
}
}
```
- For Python projects:
```bash
# Directly with command line
mcp install server.py -v API_KEY=key
# Or in settings.json
{
"mcpServers": {
"my-server": {
"command": "python",
"args": ["server.py"],
"env": {
"API_KEY": "key"
},
"disabled": false,
"autoApprove": []
}
}
}
```
## Step 3: Testing (BLOCKER ⛔️)
<thinking>
BEFORE using attempt_completion, I MUST verify:
□ Have I tested EVERY tool?
□ Have I confirmed success from the user for each test?
□ Have I documented the test results?
If ANY answer is "no", I MUST NOT use attempt_completion.
</thinking>
1. Test Each Tool (REQUIRED)
□ Test each tool with valid inputs
□ Verify output format is correct
DO NOT PROCEED UNTIL ALL TOOLS TESTED
## Step 4: Completion
❗ STOP AND VERIFY:
□ Every tool has been tested with valid inputs
□ Output format is correct for each tool
Only after ALL tools have been tested can attempt_completion be used.
## Key Requirements
- ✓ Must use MCP SDK
- ✓ Must have comprehensive logging
- ✓ Must test each tool individually
- ✓ Must handle errors gracefully
- NEVER skip testing before completionWith this .sypharules file positioned in your working directory, Sypha will:
- Initialize in PLAN MODE for server design prior to implementation
- Maintain proper implementation standards during ACT MODE
- Mandate comprehensive tool testing before permitting completion
- Navigate you through every stage of the development lifecycle
Initial Setup Process
MCP server creation involves several straightforward initial steps:
1. Establish a .sypharules file (CRITICAL)
Initially, incorporate a .sypharules file at the root level of your MCP working directory utilizing the protocol detailed above. This configuration file directs Sypha to employ the MCP development protocol within this specific folder.
2. Initiate a Chat Session with Detailed Requirements
Launch your Sypha chat session with a precise description of your intended build. Include specific details regarding:
- Your MCP server's intended purpose
- The target API or service for integration
- Required tools or specific functionality
Example description:
I want to build an MCP server for the AlphaAdvantage financial API.
It should allow me to get real-time stock data, perform technical
analysis, and retrieve company financial information.3. Progress Through the Protocol Stages
Sypha initiates automatically in PLAN MODE, directing you through the planning workflow:
- Examining the problem scope and requirements
- Analyzing API documentation
- Strategizing authentication approaches
- Architecting tool interfaces
Upon completion of planning, activate ACT MODE via the toggle control at the chat bottom to commence implementation.
4. Supply API Documentation Initially
Among the most beneficial practices for assisting Sypha in building your MCP server is providing official API documentation at the outset:
Here's the API documentation for the service:
[Paste API documentation here]Furnishing thorough API specifications (endpoints, authentication mechanisms, data structures) substantially enhances Sypha's capacity to develop a robust MCP server.
Comprehending the Dual Operating Modes
PLAN MODE
During this collaborative stage, you partner with Sypha to architect your MCP server:
- Establish the problem scope boundaries
- Select suitable APIs
- Strategize authentication methodologies
- Architect the tool interfaces
- Specify data format requirements
ACT MODE
Following the completion of planning, Sypha facilitates server implementation:
- Construct the project architecture
- Develop the implementation code
- Establish configuration settings
- Conduct thorough component testing
- Complete documentation
Case Study: AlphaAdvantage Stock Analysis Server
Let's examine the developmental journey of our AlphaAdvantage MCP server, delivering stock data analysis and comprehensive reporting capabilities.
Planning Stage

Throughout the planning stage, our approach included:
- Problem definition: Users require direct access to financial data, stock analysis, and market intelligence through their AI assistant
- API selection: AlphaAdvantage API chosen for financial market data delivery
- Standard API key authentication mechanism
- Free tier restriction of 5 requests per minute
- Multiple endpoints supporting varied financial data categories
- Tool design requirements:
- Stock overview data (present price, company information)
- Technical analysis incorporating indicators (RSI, MACD, etc.)
- Fundamental analysis (financial statements, financial ratios)
- Earnings report information
- News aggregation and sentiment analysis
- Data formatting strategy:
- Polished, well-structured markdown output
- Tabular presentation for structured datasets
- Visual trend indicators (↑/↓)
- Standardized financial number formatting
Implementation Stage

Project initialization commenced with bootstrapping:
npx @modelcontextprotocol/create-server alphaadvantage-mcp
cd alphaadvantage-mcp
npm install axios node-cacheSubsequently, we organized the project structure as follows:
src/
├── api/
│ └── alphaAdvantageClient.ts # API client with rate limiting & caching
├── formatters/
│ └── markdownFormatter.ts # Output formatters for clean markdown
└── index.ts # Main MCP server implementationAPI Client Development
The API client development encompassed:
- Rate limiting: Enforcement of the 5 requests per minute constraint
- Caching: Strategic API call reduction through intelligent caching
- Error handling: Comprehensive error detection and reporting mechanisms
- Typed interfaces: Well-defined TypeScript types across all data structures
Critical implementation specifications:
/**
* Manage rate limiting based on free tier (5 calls per minute)
*/
private async enforceRateLimit() {
if (this.requestsThisMinute >= 5) {
console.error("[Rate Limit] Rate limit reached. Waiting for next minute...");
return new Promise<void>((resolve) => {
const remainingMs = 60 * 1000 - (Date.now() % (60 * 1000));
setTimeout(resolve, remainingMs + 100); // Add 100ms buffer
});
}
this.requestsThisMinute++;
return Promise.resolve();
}Markdown Formatting
We implemented formatters to display financial data beautifully:
/**
* Format company overview into markdown
*/
export function formatStockOverview(overviewData: any, quoteData: any): string {
// Extract data
const overview = overviewData
const quote = quoteData["Global Quote"]
// Calculate price change
const currentPrice = parseFloat(quote["05. price"] || "0")
const priceChange = parseFloat(quote["09. change"] || "0")
const changePercent = parseFloat(quote["10. change percent"]?.replace("%", "") || "0")
// Format markdown
let markdown = `# ${overview.Symbol} (${overview.Name}) - ${formatCurrency(currentPrice)} ${addTrendIndicator(priceChange)}${changePercent > 0 ? "+" : ""}${changePercent.toFixed(2)}%\n\n`
// Add more details...
return markdown
}Tool Implementation
We defined five tools with clear interfaces:
server.setRequestHandler(ListToolsRequestSchema, async () => {
console.error("[Setup] Listing available tools")
return {
tools: [
{
name: "get_stock_overview",
description: "Get basic company info and current quote for a stock symbol",
inputSchema: {
type: "object",
properties: {
symbol: {
type: "string",
description: "Stock symbol (e.g., 'AAPL')",
},
market: {
type: "string",
description: "Optional market (e.g., 'US')",
default: "US",
},
},
required: ["symbol"],
},
},
// Additional tools defined here...
],
}
})Each tool's handler included:
- Input validation
- API client calls with error handling
- Markdown formatting of responses
- Comprehensive logging
Testing Stage
This essential phase required methodical testing of every tool:
- Initially, we established the MCP server configuration within the settings:
{
"mcpServers": {
"alphaadvantage-mcp": {
"command": "node",
"args": ["/path/to/alphaadvantage-mcp/build/index.js"],
"env": {
"ALPHAVANTAGE_API_KEY": "YOUR_API_KEY"
},
"disabled": false,
"autoApprove": []
}
}
}- Subsequently, individual tool testing was performed:
-
get_stock_overview: Obtained AAPL stock overview data
# AAPL (Apple Inc) - $241.84 ↑+1.91% **Sector:** TECHNOLOGY **Industry:** ELECTRONIC COMPUTERS **Market Cap:** 3.63T **P/E Ratio:** 38.26 ... -
get_technical_analysis: Acquired price action and RSI information
# Technical Analysis: AAPL ## Daily Price Action Current Price: $241.84 (↑$4.54, +1.91%) ### Recent Daily Prices | Date | Open | High | Low | Close | Volume | | ---------- | ------- | ------- | ------- | ------- | ------ | | 2025-02-28 | $236.95 | $242.09 | $230.20 | $241.84 | 56.83M | ... -
get_earnings_report: Extracted MSFT earnings history and generated formatted report
# Earnings Report: MSFT (Microsoft Corporation) **Sector:** TECHNOLOGY **Industry:** SERVICES-PREPACKAGED SOFTWARE **Current EPS:** $12.43 ## Recent Quarterly Earnings | Quarter | Date | EPS Estimate | EPS Actual | Surprise % | | ---------- | ---------- | ------------ | ---------- | ---------- | | 2024-12-31 | 2025-01-29 | $3.11 | $3.23 | ↑4.01% | ...
Obstacles and Resolutions
Throughout the development process, several challenges emerged:
- API Rate Limiting:
- Challenge: Free tier constraint of 5 calls per minute
- Solution: Deployed queuing mechanisms, enforced rate restrictions, and integrated comprehensive caching
- Data Formatting:
- Challenge: Raw API output lacked user-friendliness
- Solution: Developed formatting utilities ensuring consistent financial data presentation
- Timeout Issues:
- Challenge: Complex tools executing multiple API calls risked timeout
- Solution: Recommended decomposing complex tools into smaller components, enhanced caching optimization
Key Takeaways
Our AlphaAdvantage implementation yielded several valuable insights:
- API Limit Planning: Comprehend and architect around API rate restrictions from the outset
- Strategic Caching: Recognize high-impact caching opportunities for performance enhancement
- Readability-Focused Formatting: Prioritize quality data formatting to elevate user experience
- Comprehensive Path Testing: Verify all tools independently prior to completion
- API Complexity Management: For APIs demanding multiple calls, architect tools with narrower scopes
Essential Implementation Best Practices
Thorough Logging
Robust logging proves crucial for MCP server debugging:
// Start-up logging
console.error("[Setup] Initializing AlphaAdvantage MCP server...")
// API request logging
console.error(`[API] Getting stock overview for ${symbol}`)
// Error handling with context
console.error(`[Error] Tool execution failed: ${error.message}`)
// Cache operations
console.error(`[Cache] Using cached data for: ${cacheKey}`)Rigorous Type Definitions
Type specifications prevent errors while enhancing maintainability:
export interface AlphaAdvantageConfig {
apiKey: string
cacheTTL?: Partial<typeof DEFAULT_CACHE_TTL>
baseURL?: string
}
/**
* Validate that a stock symbol is provided and looks valid
*/
function validateSymbol(symbol: unknown): asserts symbol is string {
if (typeof symbol !== "string" || symbol.trim() === "") {
throw new McpError(ErrorCode.InvalidParams, "A valid stock symbol is required")
}
// Basic symbol validation (letters, numbers, dots)
const symbolRegex = /^[A-Za-z0-9.]+$/
if (!symbolRegex.test(symbol)) {
throw new McpError(ErrorCode.InvalidParams, `Invalid stock symbol: ${symbol}`)
}
}Smart Caching Strategies
Minimize API calls while enhancing performance:
// Default cache TTL in seconds
const DEFAULT_CACHE_TTL = {
STOCK_OVERVIEW: 60 * 60, // 1 hour
TECHNICAL_ANALYSIS: 60 * 30, // 30 minutes
FUNDAMENTAL_ANALYSIS: 60 * 60 * 24, // 24 hours
EARNINGS_REPORT: 60 * 60 * 24, // 24 hours
NEWS: 60 * 15, // 15 minutes
}
// Check cache first
const cachedData = this.cache.get<T>(cacheKey)
if (cachedData) {
console.error(`[Cache] Using cached data for: ${cacheKey}`)
return cachedData
}
// Cache successful responses
this.cache.set(cacheKey, response.data, cacheTTL)Robust Error Management
Deploy comprehensive error handling to preserve positive user experience:
try {
switch (request.params.name) {
case "get_stock_overview": {
// Implementation...
}
// Other cases...
default:
throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`)
}
} catch (error) {
console.error(`[Error] Tool execution failed: ${error instanceof Error ? error.message : String(error)}`)
if (error instanceof McpError) {
throw error
}
return {
content: [
{
type: "text",
text: `Error: ${error instanceof Error ? error.message : String(error)}`,
},
],
isError: true,
}
}MCP Resources
Resources enable your MCP servers to present data to Sypha without code execution. They serve ideally for supplying contextual information such as files, API responses, or database records that Sypha can consult throughout conversations.
Incorporating Resources into Your MCP Server
- Specify the resources your server will make available:
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: [
{
uri: "file:///project/readme.md",
name: "Project README",
mimeType: "text/markdown",
},
],
}
})- Develop read handlers for content delivery:
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
if (request.params.uri === "file:///project/readme.md") {
const content = await fs.promises.readFile("/path/to/readme.md", "utf-8")
return {
contents: [
{
uri: request.params.uri,
mimeType: "text/markdown",
text: content,
},
],
}
}
throw new Error("Resource not found")
})Resources enhance your MCP servers' contextual awareness, permitting Sypha to retrieve specific information without manual copy/paste operations. For additional details, consult the official documentation.
Frequent Challenges and Their Solutions
API Authentication Complexity
Challenge: APIs frequently implement varying authentication approaches.
Solution:
- For API key authentication, utilize environment variables within MCP configuration
- For OAuth authentication, develop a dedicated script for refresh token acquisition
- Maintain secure storage of sensitive tokens
// Authenticate using API key from environment
const API_KEY = process.env.ALPHAVANTAGE_API_KEY
if (!API_KEY) {
console.error("[Error] Missing ALPHAVANTAGE_API_KEY environment variable")
process.exit(1)
}
// Initialize API client
const apiClient = new AlphaAdvantageClient({
apiKey: API_KEY,
})Incomplete or Restricted API Capabilities
Challenge: APIs may lack complete functionality required for your needs.
Solution:
- Deploy fallback mechanisms utilizing available endpoints
- Construct simulated functionality when necessary
- Transform API data to align with your requirements
API Rate Restriction
Challenge: The majority of APIs enforce rate limits that may trigger failures.
Solution:
- Deploy appropriate rate limiting mechanisms
- Integrate intelligent caching systems
- Ensure graceful degradation
- Provide transparent error messaging regarding rate limits
if (this.requestsThisMinute >= 5) {
console.error("[Rate Limit] Rate limit reached. Waiting for next minute...")
return new Promise<void>((resolve) => {
const remainingMs = 60 * 1000 - (Date.now() % (60 * 1000))
setTimeout(resolve, remainingMs + 100) // Add 100ms buffer
})
}Supplementary Resources
MCP Overview
Explore Model Context Protocol (MCP) servers, their features, and how Sypha facilitates building and utilizing them. MCP establishes standardization for how applications deliver context to LLMs, functioning like a USB-C port for AI applications.
MCP Transport Mechanisms
Discover the two core transport methods enabling communication between Sypha and MCP servers: Standard Input/Output (STDIO) and Server-Sent Events (SSE). Both offer unique features, benefits, and ideal applications.