发现优秀的 MCP 服务器

通过 MCP 服务器扩展您的代理能力,拥有 17,457 个能力。

研究与数据1,246
Spotify-Agent

Spotify-Agent

Okay, this is a complex project, and I can't provide you with a complete, ready-to-run MCP (Minecraft Protocol) server implementation here. Building a full MCP server with Spotify, Last.fm, and internet integration for music recommendations requires significant coding effort and knowledge of several technologies. However, I can give you a detailed outline, code snippets (in Python, as it's commonly used for these tasks), and guidance to get you started. **I. Project Overview** The goal is to create an MCP server plugin (or a standalone server that interacts with a Minecraft server) that: 1. **Connects to Spotify and Last.fm APIs:** Retrieves user listening history, track information, artist information, and similar artist data. 2. **Interacts with the Internet (e.g., for Lyrics):** Fetches lyrics for songs. 3. **Stores and Processes Music Data:** Creates a database or data structure to store user preferences, track information, and recommendation data. 4. **Provides Minecraft Commands:** Allows players to request recommendations, view their listening history, and interact with the music system within the game. 5. **Delivers Recommendations:** Generates music recommendations based on user data and similarity algorithms. **II. Technology Stack** * **Minecraft Server:** You'll need a Minecraft server (e.g., Spigot, Paper, Fabric). Choose one you're comfortable with. * **MCP Server Library/Framework:** Choose a library that simplifies MCP server development. Popular options include: * **Python:** `mcstatus`, `nbt`, `minecraft-protocol` (for lower-level control) * **Java:** Spigot API, Paper API (if you're building a plugin) * **Programming Language:** Python or Java are good choices. Python is often preferred for scripting and API interactions. * **Spotify API:** Use the Spotify Web API (requires a Spotify Developer account). * **Last.fm API:** Use the Last.fm API (requires a Last.fm API key). * **Lyrics API (Optional):** Consider using a lyrics API like Lyrics.ovh or Musixmatch API. * **Database (Optional):** Consider using a database (e.g., SQLite, MySQL, PostgreSQL) to store user data and music information. SQLite is a good choice for smaller projects. * **Recommendation Algorithm:** Implement a recommendation algorithm (e.g., collaborative filtering, content-based filtering, hybrid approach). **III. Detailed Steps and Code Snippets (Python Example)** **1. Setting up the MCP Server (Python)** ```python import socket import struct import json import threading # Configuration HOST = 'localhost' PORT = 25565 # Default Minecraft port def handle_client(conn, addr): print(f"Connected by {addr}") try: # Handshake data = conn.recv(256) packet_length = struct.unpack('>i', data[:4])[0] packet_id = struct.unpack('>b', data[4:5])[0] if packet_id == 0x00: # Handshake packet handshake_data = json.loads(data[5:].decode('utf-8')) print(f"Handshake data: {handshake_data}") # Status Request data = conn.recv(256) packet_length = struct.unpack('>i', data[:4])[0] packet_id = struct.unpack('>b', data[4:5])[0] if packet_id == 0x00: # Status Request # Respond with server status status = { "version": { "name": "My Music Server", "protocol": 754 # Example protocol version }, "players": { "max": 100, "online": 0, "sample": [] }, "description": { "text": "A server for music recommendations!" } } status_json = json.dumps(status) status_bytes = status_json.encode('utf-8') status_length = len(status_bytes) response = struct.pack('>i', status_length + 1) + struct.pack('>b', 0x00) + status_bytes conn.sendall(response) # Ping Request data = conn.recv(256) packet_length = struct.unpack('>i', data[:4])[0] packet_id = struct.unpack('>b', data[4:5])[0] if packet_id == 0x01: # Ping Request ping_payload = data[5:] response = struct.pack('>i', len(ping_payload) + 1) + struct.pack('>b', 0x01) + ping_payload conn.sendall(response) except Exception as e: print(f"Error handling client: {e}") finally: conn.close() print(f"Connection closed with {addr}") def start_server(): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Allow reuse of the address server_socket.bind((HOST, PORT)) server_socket.listen(5) print(f"Server listening on {HOST}:{PORT}") while True: conn, addr = server_socket.accept() client_thread = threading.Thread(target=handle_client, args=(conn, addr)) client_thread.start() if __name__ == "__main__": start_server() ``` **Explanation:** * **`socket`:** Creates a socket for network communication. * **`struct`:** Packs and unpacks data in binary format (required for the Minecraft protocol). * **`json`:** Handles JSON data for the server status. * **`threading`:** Allows handling multiple client connections concurrently. * **`handle_client`:** This function handles the communication with a single Minecraft client. It receives the handshake, status request, and ping request, and sends back the appropriate responses. * **`start_server`:** Sets up the server socket and listens for incoming connections. **Important:** This is a *very* basic MCP server. It only handles the handshake, status request, and ping request. You'll need to implement the full Minecraft protocol to handle player login, chat messages, commands, and other game events. **2. Integrating with Spotify and Last.fm APIs** ```python import spotipy from spotipy.oauth2 import SpotifyClientCredentials import pylast # Spotify API Credentials (replace with your own) SPOTIPY_CLIENT_ID = "YOUR_SPOTIFY_CLIENT_ID" SPOTIPY_CLIENT_SECRET = "YOUR_SPOTIFY_CLIENT_SECRET" # Last.fm API Credentials (replace with your own) LASTFM_API_KEY = "YOUR_LASTFM_API_KEY" LASTFM_API_SECRET = "YOUR_LASTFM_API_SECRET" # Initialize Spotify client client_credentials_manager = SpotifyClientCredentials(client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET) sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) # Initialize Last.fm network network = pylast.LastFMNetwork( api_key=LASTFM_API_KEY, api_secret=LASTFM_API_SECRET, username="YOUR_LASTFM_USERNAME" # Replace with a Last.fm username for testing ) def get_spotify_track_info(track_name, artist_name): """Searches Spotify for a track and returns track information.""" query = f"track:{track_name} artist:{artist_name}" results = sp.search(q=query, type='track', limit=1) if results['tracks']['items']: track = results['tracks']['items'][0] return { 'id': track['id'], 'name': track['name'], 'artist': track['artists'][0]['name'], 'album': track['album']['name'], 'popularity': track['popularity'], 'uri': track['uri'] } else: return None def get_lastfm_recent_tracks(username): """Gets the recent tracks played by a Last.fm user.""" user = network.get_user(username) recent_tracks = user.get_recent_tracks(limit=10) # Get the last 10 tracks tracks = [] for item in recent_tracks: track = item.track tracks.append({ 'artist': track.artist.name, 'title': track.title }) return tracks # Example usage if __name__ == "__main__": # Spotify Example track_info = get_spotify_track_info("Bohemian Rhapsody", "Queen") if track_info: print("Spotify Track Info:", track_info) else: print("Track not found on Spotify.") # Last.fm Example recent_tracks = get_lastfm_recent_tracks("YOUR_LASTFM_USERNAME") # Replace with your Last.fm username print("\nLast.fm Recent Tracks:") for track in recent_tracks: print(f"- {track['artist']} - {track['title']}") ``` **Explanation:** * **`spotipy`:** The Spotify API library. You'll need to install it: `pip install spotipy` * **`pylast`:** The Last.fm API library. You'll need to install it: `pip install pylast` * **API Credentials:** You *must* replace the placeholder credentials with your own API keys and secrets from the Spotify Developer Dashboard and the Last.fm API page. * **`get_spotify_track_info`:** Searches Spotify for a track and returns information like ID, name, artist, album, and popularity. * **`get_lastfm_recent_tracks`:** Gets the recent tracks played by a Last.fm user. **3. Handling Minecraft Commands** You'll need to integrate your music functionality with Minecraft commands. The specific way to do this depends on the MCP server library you're using. Here's a general outline: * **Command Registration:** Register a new command (e.g., `/musicrecommend`, `/mylistenhistory`). * **Command Parsing:** Parse the arguments provided with the command. * **Command Execution:** Execute the appropriate music-related function based on the command and arguments. * **Response to Player:** Send a message back to the player in the Minecraft chat window with the results (e.g., the recommended songs, their listening history). **Example (Conceptual - using a hypothetical MCP library):** ```python # Hypothetical MCP library functions def register_command(command_name, command_handler): # Registers a command with the server pass def send_message_to_player(player_name, message): # Sends a message to a player in the game pass def handle_music_recommend_command(player_name, args): # Get the player's Last.fm username (from a database or configuration) lastfm_username = get_player_lastfm_username(player_name) if not lastfm_username: send_message_to_player(player_name, "Please link your Last.fm account first.") return # Get the player's recent tracks from Last.fm recent_tracks = get_lastfm_recent_tracks(lastfm_username) # Generate recommendations (implementation details omitted) recommendations = generate_recommendations(recent_tracks) # Format the recommendations into a message message = "Recommended Songs:\n" for track in recommendations: message += f"- {track['artist']} - {track['title']}\n" # Send the recommendations to the player send_message_to_player(player_name, message) def get_player_lastfm_username(player_name): # This function would retrieve the Last.fm username associated with the player # from a database or configuration file. # For example: # player_data = database.get_player_data(player_name) # return player_data.get('lastfm_username') return "YOUR_LASTFM_USERNAME" # Replace with your Last.fm username for testing # Register the command register_command("musicrecommend", handle_music_recommend_command) ``` **4. Recommendation Algorithm** This is the most complex part. Here are some approaches: * **Collaborative Filtering:** Find users with similar listening habits and recommend songs they like that the current user hasn't heard. Requires a database of user listening data. * **Content-Based Filtering:** Analyze the characteristics of the songs the user likes (e.g., genre, tempo, mood) and recommend songs with similar characteristics. You can use the Spotify API to get track features. * **Hybrid Approach:** Combine collaborative and content-based filtering for better results. **Example (Simplified Content-Based Filtering):** ```python def generate_recommendations(recent_tracks): """Generates recommendations based on recent tracks.""" recommendations = [] for track in recent_tracks: # Get Spotify track info track_info = get_spotify_track_info(track['title'], track['artist']) if track_info: # Get similar artists from Spotify artist_id = sp.artist(track_info['uri'].split(':')[2])['artists'][0]['id'] related_artists = sp.artist_related_artists(artist_id)['artists'] # Get top tracks from related artists for artist in related_artists[:3]: # Limit to 3 related artists top_tracks = sp.artist_top_tracks(artist['id'])['tracks'][:2] # Limit to 2 tracks for top_track in top_tracks: recommendations.append({ 'artist': top_track['artists'][0]['name'], 'title': top_track['name'] }) return recommendations ``` **5. Database (Optional)** If you want to store user data (e.g., Last.fm usernames, listening history), you'll need a database. SQLite is a good choice for smaller projects. ```python import sqlite3 # Database setup conn = sqlite3.connect('music_server.db') cursor = conn.cursor() # Create a table to store player data cursor.execute(''' CREATE TABLE IF NOT EXISTS players ( player_name TEXT PRIMARY KEY, lastfm_username TEXT ) ''') conn.commit() def set_player_lastfm_username(player_name, lastfm_username): """Sets the Last.fm username for a player in the database.""" cursor.execute("INSERT OR REPLACE INTO players (player_name, lastfm_username) VALUES (?, ?)", (player_name, lastfm_username)) conn.commit() def get_player_lastfm_username(player_name): """Gets the Last.fm username for a player from the database.""" cursor.execute("SELECT lastfm_username FROM players WHERE player_name = ?", (player_name,)) result = cursor.fetchone() if result: return result[0] else: return None # Example usage if __name__ == "__main__": set_player_lastfm_username("Player123", "YOUR_LASTFM_USERNAME") # Replace with your Last.fm username username = get_player_lastfm_username("Player123") print(f"Last.fm username for Player123: {username}") conn.close() ``` **IV. Key Considerations and Challenges** * **Minecraft Protocol:** Understanding the Minecraft protocol is crucial for building a functional MCP server. It's complex and constantly evolving. * **API Rate Limits:** The Spotify and Last.fm APIs have rate limits. You need to handle these limits gracefully to avoid being blocked. Implement caching and throttling. * **User Authentication:** You'll need a way for players to link their Spotify/Last.fm accounts to their Minecraft accounts. This typically involves OAuth 2.0. * **Data Storage:** Choosing the right data storage solution (database, file system, etc.) depends on the scale of your project. * **Performance:** Generating recommendations can be computationally expensive. Optimize your code and consider using background threads or asynchronous tasks. * **Error Handling:** Implement robust error handling to deal with API errors, network issues, and invalid user input. * **Security:** Protect API keys and user data. Don't store sensitive information in plain text. * **Scalability:** If you plan to support a large number of users, you'll need to design your system to be scalable. **V. Next Steps** 1. **Choose an MCP Server Library:** Select a library that suits your needs and programming language preference. 2. **Implement the Basic MCP Server:** Get a basic MCP server running that can handle the handshake, status request, and ping request. 3. **Integrate with the Spotify and Last.fm APIs:** Implement the functions to retrieve user listening history and track information. 4. **Implement Command Handling:** Add the ability to register and handle Minecraft commands. 5. **Implement a Recommendation Algorithm:** Start with a simple algorithm and gradually improve it. 6. **Add a Database (Optional):** If you need to store user data, set up a database. 7. **Test Thoroughly:** Test your server with multiple Minecraft clients and different scenarios. **VI. Chinese Translation of Key Terms** Here's a translation of some key terms that might be helpful: * **MCP Server:** MCP服务器 (MCP fúwùqì) * **Spotify API:** Spotify API (Spotify API) (Note: API is often used directly in Chinese) * **Last.fm API:** Last.fm API (Last.fm API) * **Recommendation Algorithm:** 推荐算法 (tuījiàn suànfǎ) * **Minecraft Command:** Minecraft 命令 (Minecraft mìnglìng) * **Listening History:** 听歌历史 (tīng gē lìshǐ) * **API Key:** API 密钥 (API mìyào) * **Database:** 数据库 (shùjùkù) * **User Authentication:** 用户认证 (yònghù rènzhèng) * **Rate Limit:** 速率限制 (sùlǜ xiànzhì) or 频率限制 (pínlǜ xiànzhì) * **Collaborative Filtering:** 协同过滤 (xiétóng guòlǜ) * **Content-Based Filtering:** 基于内容的过滤 (jī yú nèiróng de guòlǜ) This is a substantial project, but by breaking it down into smaller steps and using the resources and guidance provided, you can make progress towards building your music recommendation MCP server. Good luck!

Awesome MCP Servers

Awesome MCP Servers

很棒的 MCP 服务器 - 一个精选的模型上下文协议服务器列表

StrongApps_MCPE_servers

StrongApps_MCPE_servers

镜子 (jìng zi)

Korea Tour MCP Server

Korea Tour MCP Server

韩国旅游信息 MCP 服务器

MCP AI Infra Real Time Agent

MCP AI Infra Real Time Agent

开发了一种基于 MCP 的 AI 基础设施,该基础设施能够为 Claude 和 Cursor 等 AI 客户端提供实时工具执行、结构化知识检索和动态代理交互。

MetaTrader 5 MCP Server

MetaTrader 5 MCP Server

test-repo-from-custom-mcp

test-repo-from-custom-mcp

由自定义 MCP 服务器创建的测试存储库

MCP SERVER LIMS

MCP SERVER LIMS

MCP 工具用于实验室信息管理系统。 (MCP gōngjù yòng yú shíyànshì xìnxī guǎnlǐ xìtǒng.)

eth-mcp-server

eth-mcp-server

一个痴迷以太坊的MCP服务器,创建者仍在思考它的最终用途。目前,这只是为了好玩!

yfinance MCP Server

yfinance MCP Server

将金融数据从 yfinance 获取到 Claude Desktop 的 MCP 服务器

Bucket Feature Flags MCP Server

Bucket Feature Flags MCP Server

在你的代码编辑器中,直接从聊天中标记功能,包括 VS Code、Cursor、Windsurf、Claude Code——任何支持 MCP 的 IDE。

Model Context Protocol Server For Cyber Security

Model Context Protocol Server For Cyber Security

网络安全模型上下文协议服务器

AWorld

AWorld

轻松构建、评估和运行通用多智能体助手

mcp-server

mcp-server

🎓 Canvas LMS MCP Server 🎓

🎓 Canvas LMS MCP Server 🎓

为学生提供访问 Canvas LMS 的 MCP 服务器

Brain Server - MCP Knowledge Embedding Service

Brain Server - MCP Knowledge Embedding Service

Spotify MCP Server

Spotify MCP Server

镜子 (jìng zi)

Demo

Demo

eRegulations MCP Server

eRegulations MCP Server

Microsoft 365 File Search MCP Server (SharePoint & OneDrive)

Microsoft 365 File Search MCP Server (SharePoint & OneDrive)

Pokemon TCG Card Search MCP

Pokemon TCG Card Search MCP

一个模型上下文协议服务器,允许 Claude 搜索和显示宝可梦集换式卡牌游戏卡牌,并按名称、类型、合法性和统计数据等属性进行过滤。 (Or, a slightly more formal/technical translation:) 一个模型上下文协议服务器,用于允许 Claude 搜索并展示宝可梦集换式卡牌游戏卡牌,支持按名称、类型、合法性和统计数据等属性进行筛选。

Google Analytics Data API MCP Server

Google Analytics Data API MCP Server

ElevenLabs Scribe MCP Server

ElevenLabs Scribe MCP Server

ElevenLabs Scribe ASR API 的模型控制协议 (MCP) 服务器

A Simple MCP Weather Server written in Python

A Simple MCP Weather Server written in Python

Baidu AI Search

Baidu AI Search

百度 AI 搜索将百度搜索引擎与 LLM 模型相结合,以找到针对您查询的最佳响应。请访问 https://github.com/baidubce/app-builder/tree/master/python/mcp_server/ai_search 和 https://cloud.baidu.com/doc/AppBuilder/s/zm8pn5cju 查看详情。

Интеграция Strava API с Model Context Protocol (MCP) SDK

Интеграция Strava API с Model Context Protocol (MCP) SDK

镜子 (jìng zi)

ZZZHDW_mcp Server Kusto

ZZZHDW_mcp Server Kusto

镜子 (jìng zi)

Steam MCP Server (Node.js/TypeScript)

Steam MCP Server (Node.js/TypeScript)

用于 Steam Web API 游戏统计的 MCP 服务器

Github

Github

FastDomainCheck MCP Server

FastDomainCheck MCP Server

用于批量检查域名注册状态的模型上下文协议。