Das Model Context Protocol (MCP) revolutioniert die Art und Weise, wie KI-Modelle mit externen Tools interagieren. In diesem umfassenden Tutorial erfahren Sie, wie Sie einen leistungsstarken MCP Server entwickeln, der Dateisystem, Datenbank und APIs nahtlos integriert – alles mit der Kosteneffizienz von HolySheep AI.

HolySheep vs. Offizielle APIs vs. Andere Relay-Dienste

Bevor wir in die technische Umsetzung einsteigen, lohnt sich ein Blick auf die wirtschaftlichen Vorteile der verschiedenen Anbieter:

KriteriumHolySheep AIOffizielle APIsAndere Relay-Dienste
Wechselkurs¥1 = $1 (85%+ Ersparnis)$1 = $1$1 = $1
ZahlungsmethodenWeChat/Alipay/KreditkarteNur KreditkarteKreditkarte/Limited
Latenz<50ms100-300ms80-200ms
StartguthabenKostenlose Credits$5-18 GuthabenVariabel
GPT-4.1$8/MTok$15-30/MTok$10-20/MTok
Claude Sonnet 4.5$15/MTok$30/MTok$18-25/MTok
Gemini 2.5 Flash$2.50/MTok$3.50/MTok$3/MTok
DeepSeek V3.2$0.42/MTok$0.55/MTok$0.50/MTok

Was ist MCP und warum ist es relevant?

Das Model Context Protocol ist ein offener Standard, der es KI-Anwendungen ermöglicht, mit externen Tools und Datenquellen zu kommunizieren. Im Gegensatz zu proprietären Lösungen bietet MCP eine standardisierte Schnittstelle, die Flexibilität und Wiederverwendbarkeit gewährleistet.

Projektstruktur unseres MCP Servers

Unser三合一 (Drei-in-Eins) MCP Server wird folgende Kernfunktionen besitzen:

Voraussetzungen und Installation

# Node.js-Projekt initialisieren
mkdir mcp-trinity-server
cd mcp-trinity-server
npm init -y

Abhängigkeiten installieren

npm install @modelcontextprotocol/sdk better-sqlite3 node-fetch zod

TypeScript-Konfiguration

npm install -D typescript @types/node @types/better-sqlite3 tsx npx tsc --init

Grundlegender MCP Server mit TypeScript

Zunächst erstellen wir die Basisstruktur unseres MCP Servers:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

// Server-Initialisierung mit HolySheep AI
const server = new McpServer({
  name: "Trinity MCP Server",
  version: "1.0.0",
});

// Konfiguration für HolySheep AI
const HOLYSHEEP_CONFIG = {
  baseUrl: "https://api.holysheep.ai/v1",
  apiKey: process.env.HOLYSHEEP_API_KEY || "YOUR_HOLYSHEEP_API_KEY",
};

console.log("🚀 Trinity MCP Server gestartet mit HolySheep AI");
console.log(📡 Endpunkt: ${HOLYSHEEP_CONFIG.baseUrl});

FileSystem Tool implementieren

Das Dateisystem-Tool ermöglicht grundlegende Dateioperationen:

import { promises as fs } from "fs";
import path from "path";

// FileSystem Tool registrieren
server.setRequestHandler(
  { method: "tools/list" },
  async () => ({
    tools: [
      {
        name: "read_file",
        description: "Dateiinhalt lesen",
        inputSchema: {
          type: "object",
          properties: {
            path: { type: "string", description: "Dateipfad" },
          },
          required: ["path"],
        },
      },
      {
        name: "write_file",
        description: "Inhalt in Datei schreiben",
        inputSchema: {
          type: "object",
          properties: {
            path: { type: "string", description: "Zieldateipfad" },
            content: { type: "string", description: "Dateinhalt" },
          },
          required: ["path", "content"],
        },
      },
      {
        name: "list_directory",
        description: "Verzeichnisinhalt auflisten",
        inputSchema: {
          type: "object",
          properties: {
            path: { type: "string", description: "Verzeichnispfad" },
          },
          required: ["path"],
        },
      },
    ],
  })
);

// Tool-Ausführungen behandeln
server.setRequestHandler(
  { method: "tools/call" },
  async (request: { params: { name: string; arguments: Record } }) => {
    const { name, arguments: args } = request.params;

    switch (name) {
      case "read_file": {
        const content = await fs.readFile(args.path as string, "utf-8");
        return { content: [{ type: "text", text: content }] };
      }
      
      case "write_file": {
        await fs.writeFile(args.path as string, args.content as string);
        return { content: [{ type: "text", text: ✓ Datei geschrieben: ${args.path} }] };
      }
      
      case "list_directory": {
        const entries = await fs.readdir(args.path as string, { withFileTypes: true });
        const result = entries.map(e => 
          ${e.isDirectory() ? "📁" : "📄"} ${e.name}
        ).join("\n");
        return { content: [{ type: "text", text: result }] };
      }
      
      default:
        throw new Error(Unbekanntes Tool: ${name});
    }
  }
);

Database Tool mit SQLite

Das Datenbank-Tool integriert SQLite für persistente Datenspeicherung:

import Database from "better-sqlite3";

const db = new Database(":memory:");

// Datenbank-Tool registrieren
const dbToolHandler = async () => ({
  tools: [
    {
      name: "db_query",
      description: "SQL-Abfrage ausführen",
      inputSchema: {
        type: "object",
        properties: {
          sql: { type: "string", description: "SQL-Query" },
          params: { 
            type: "array", 
            description: "Query-Parameter",
            items: { type: "string" }
          },
        },
        required: ["sql"],
      },
    },
    {
      name: "db_create_table",
      description: "Neue Tabelle erstellen",
      inputSchema: {
        type: "object",
        properties: {
          name: { type: "string", description: "Tabellenname" },
          columns: { type: "string", description: "Spaltendefinitionen" },
        },
        required: ["name", "columns"],
      },
    },
  ],
});

server.setRequestHandler({ method: "tools/list" }, async () => ({
  tools: [
    ...(await dbToolHandler()).tools,
    // FileSystem-Tools hier integriert
  ],
}));

API-Tool für externe HTTP-Requests

Das API-Tool ermöglicht Kommunikation mit externen Diensten:

import fetch from "node-fetch";

const apiToolHandler = {
  tools: [
    {
      name: "http_request",
      description: "HTTP-Request an externe API senden",
      inputSchema: {
        type: "object",
        properties: {
          url: { type: "string", description: "Ziel-URL" },
          method: { 
            type: "string", 
            enum: ["GET", "POST", "PUT", "DELETE"],
            default: "GET"
          },
          headers: { type: "object", description: "HTTP-Header" },
          body: { type: "string", description: "Request-Body (JSON)" },
        },
        required: ["url"],
      },
    },
  ],
};

// Integration mit HolySheep AI für KI-Antworten
async function queryAI(prompt: string, context?: string) {
  const response = await fetch(${HOLYSHEEP_CONFIG.baseUrl}/chat/completions, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": Bearer ${HOLYSHEEP_CONFIG.apiKey},
    },
    body: JSON.stringify({
      model: "gpt-4.1",
      messages: [
        { role: "system", content: "Du bist ein Assistent." },
        { role: "user", content: context ? ${context}\n\n${prompt} : prompt },
      ],
      temperature: 0.7,
    }),
  });

  const data = await response.json();
  return data.choices[0]?.message?.content || "Keine Antwort erhalten";
}

Vollständiger Server mit allen Tools

// main.ts - Komplette Server-Implementierung
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { promises as fs } from "fs";
import Database from "better-sqlite3";
import fetch from "node-fetch";
import { z } from "zod";

// HolySheep AI Konfiguration
const HOLYSHEEP = {
  baseUrl: "https://api.holysheep.ai/v1",
  apiKey: process.env.HOLYSHEEP_API_KEY,
};

// Server erstellen
const server = new McpServer({
  name: "Trinity-MCP-Server",
  version: "1.0.0",
});

// Datenbank initialisieren
const db = new Database("./data.db");
db.exec(`
  CREATE TABLE IF NOT EXISTS mcp_logs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    tool TEXT,
    args TEXT,
    result TEXT,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
  )
`);

// Tool-Liste definieren
const allTools = [
  // FileSystem Tools
  {
    name: "read_file",
    description: "Datei lesen",
    inputSchema: {
      type: "object",
      properties: { path: { type: "string" } },
      required: ["path"],
    },
  },
  {
    name: "write_file",
    description: "Datei schreiben",
    inputSchema: {
      type: "object",
      properties: {
        path: { type: "string" },
        content: { type: "string" },
      },
      required: ["path", "content"],
    },
  },
  // Database Tools
  {
    name: "db_query",
    description: "SQL-Query ausführen",
    inputSchema: {
      type: "object",
      properties: { sql: { type: "string" } },
      required: ["sql"],
    },
  },
  // API Tools
  {
    name: "ai_complete",
    description: "KI-Assistent über HolySheep AI",
    inputSchema: {
      type: "object",
      properties: {
        prompt: { type: "string" },
        model: { type: "string", default: "gpt-4.1" },
      },
      required: ["prompt"],
    },
  },
];

// Request Handler registrieren
server.setRequestHandler({ method: "tools/list" }, async () => ({
  tools: allTools,
}));

server.setRequestHandler(
  { method: "tools/call" },
  async (request: { params: { name: string; arguments: Record } }) => {
    const { name, arguments: args } = request.params;

    try {
      let result: string;

      switch (name) {
        case "read_file":
          result = await fs.readFile(args.path as string, "utf-8");
          break;

        case "write_file":
          await fs.writeFile(args.path as string, args.content as string);
          result = ✓ Gespeichert: ${args.path};
          break;

        case "db_query":
          const stmt = db.prepare(args.sql as string);
          const rows = stmt.all();
          result = JSON.stringify(rows, null, 2);
          break;

        case "ai_complete":
          const response = await fetch(${HOLYSHEEP.baseUrl}/chat/completions, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "Authorization": Bearer ${HOLYSHEEP.apiKey},
            },
            body: JSON.stringify({
              model: args.model || "gpt-4.1",
              messages: [{ role: "user", content: args.prompt }],
            }),
          });
          const data = await response.json();
          result = data.choices[0]?.message?.content || "Keine Antwort";
          break;

        default:
          throw new Error(Unbekanntes Tool: ${name});
      }

      // Log in Datenbank
      const logStmt = db.prepare(
        "INSERT INTO mcp_logs (tool, args, result) VALUES (?, ?, ?)"
      );
      logStmt.run(name, JSON.stringify(args), result.substring(0, 500));

      return { content: [{ type: "text", text: result }] };
    } catch (error) {
      return {
        content: [{ type: "text", text: Fehler: ${error} }],
        isError: true,
      };
    }
  }
);

// Server starten
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.log("✅ Trinity MCP Server aktiv auf Standard-IO");
}

main().catch(console.error);

Client-Konfiguration für Claude Desktop

Um den MCP Server mit Claude Desktop zu nutzen, konfigurieren Sie die claude_desktop_config.json:

{
  "mcpServers": {
    "trinity": {
      "command": "npx",
      "args": ["tsx", "pfad/zum/main.ts"],
      "env": {
        "HOLYSHEEP_API_KEY": "YOUR_HOLYSHEEP_API_KEY"
      }
    }