# Directory Structure
```
├── .gitignore
├── dist
│ └── server.js
├── LICENSE.txt
├── package-lock.json
├── package.json
├── README.md
├── src
│ ├── index.ts
│ └── server.ts
└── tsconfig.json
```
# Files
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
```
node_modules/
dist/
*.log
```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
```markdown
# mcp-time
A simple MCP server for getting current time in various formats. This server is designed to work with Claude desktop app on macOS.
## Features
- Get current time in YYYYMMDDHHMMSS format
- Returns time in JST (Japan Standard Time)
- Utilizes macOS system date command
## Installation
```bash
npm install mcp-time
```
## Usage
Start the server:
```bash
npm start
```
The server will start on port 3200 by default.
## Development
1. Clone the repository
2. Install dependencies
```bash
npm install
```
3. Start development server
```bash
npm run dev
```
## License
MIT License - see [LICENSE](LICENSE.txt) for details
```
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
```json
{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"moduleResolution": "node",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.test.ts"]
}
```
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
```json
{
"name": "mcp-time",
"version": "1.0.0",
"description": "MCP server for getting current time",
"main": "dist/server.js",
"type": "module",
"scripts": {
"build": "tsc && chmod +x dist/server.js",
"prepare": "npm run build"
},
"keywords": [
"mcp",
"time",
"server"
],
"author": "zepar",
"license": "MIT",
"dependencies": {
"@modelcontextprotocol/sdk": "1.0.1",
"zod-to-json-schema": "^3.23.5"
},
"devDependencies": {
"@types/node": "^20.11.0",
"ts-node": "^10.9.2",
"typescript": "^5.7.3"
},
"bin": {
"mcp-time": "dist/server.js"
}
}
```
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
```
MIT License
Copyright (c) 2024 zepar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
--------------------------------------------------------------------------------
/src/server.ts:
--------------------------------------------------------------------------------
```typescript
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
// Schema definition for getCurrentTime
const GetTimeArgsSchema = z.object({});
const server = new Server({
name: "time-server",
version: "0.1.0",
}, {
capabilities: {
tools: {},
},
});
// Tool handlers
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "getCurrentTime",
description: "Get current time in UTC",
inputSchema: zodToJsonSchema(GetTimeArgsSchema),
},
],
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
try {
const { name } = request.params;
if (name === "getCurrentTime") {
const time = new Date().toISOString();
return {
content: [{
type: "text",
text: time
}],
isError: false,
};
}
throw new Error(`Unknown tool: ${name}`);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
content: [{ type: "text", text: `Error: ${errorMessage}` }],
isError: true,
};
}
});
// Start server
async function runServer() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Time server running on stdio");
}
runServer().catch((error) => {
console.error("Fatal error running server:", error);
process.exit(1);
});
```
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
```typescript
#!/usr/bin/env node
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
interface JsonRpcRequest {
jsonrpc: '2.0';
id: number | string | null;
method: string;
params?: any;
}
interface JsonRpcResponse {
jsonrpc: '2.0';
id: number | string | null;
result?: any;
error?: {
code: number;
message: string;
data?: any;
};
}
interface TimeResponse {
time: string;
success: boolean;
}
async function handleJsonRpcMessage(message: JsonRpcRequest): Promise<JsonRpcResponse> {
if (message.method === 'getCurrentTime') {
try {
const { stdout } = await execAsync('date "+%Y-%m-%d %H:%M:%S"');
return {
jsonrpc: '2.0',
id: message.id,
result: {
time: stdout.trim(),
success: true
}
};
} catch (error) {
return {
jsonrpc: '2.0',
id: message.id,
error: {
code: -32603,
message: 'Failed to get current time',
data: error instanceof Error ? error.message : String(error)
}
};
}
}
return {
jsonrpc: '2.0',
id: message.id,
error: {
code: -32601,
message: 'Method not found'
}
};
}
// メインのサーバー処理
process.stdin.setEncoding('utf-8');
let buffer = '';
process.stdin.on('data', async (chunk: string) => {
buffer += chunk;
const messages = buffer.split('\n');
buffer = messages.pop() || '';
for (const message of messages) {
try {
const request: JsonRpcRequest = JSON.parse(message);
const response = await handleJsonRpcMessage(request);
console.log(JSON.stringify(response));
} catch (error) {
console.log(JSON.stringify({
jsonrpc: '2.0',
id: null,
error: {
code: -32700,
message: 'Parse error',
data: error instanceof Error ? error.message : String(error)
}
}));
}
}
});
process.stdin.on('end', () => {
process.exit(0);
});
// エラーハンドリング
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
```