简介
TinyURL MCP 是一个轻量级的 API 连接器,它允许你通过简单的接口将 TinyURL 的短链接生成功能集成到各种应用中。这个工具利用 FastMCP 框架构建,为开发者提供了一种便捷的方式来创建短链接。
功能特点
- 简单易用: 通过简洁的 API 接口快速生成短链接
- API 集成: 直接与 TinyURL 官方 API 对接
- 错误处理: 内置完善的错误处理和日志记录
- 类型安全: 使用 Zod 进行参数验证,确保输入数据的类型安全
技术栈
- TypeScript
- FastMCP (Model Connector Protocol 框架)
- Zod (类型验证)
- TinyURL API
关于 FastMCP
FastMCP 是一个高效的 Model Connector Protocol 实现框架,专为构建 AI 模型与第三方 API 之间的连接器而设计。它具有以下核心优势:
核心特性
- 标准化接口: 提供统一的工具注册和调用接口,简化 API 集成流程
- 类型安全: 与 Zod 深度集成,在运行时进行类型验证,避免数据不一致问题
- 多传输支持: 支持多种通信方式,包括标准输入/输出流、HTTP、WebSocket 等
- 轻量灵活: 极简设计理念,核心库体积小,易于集成到现有项目
- 强大的工具系统: 允许开发者轻松注册自定义功能,拓展应用能力
工作原理
FastMCP 通过以下步骤工作:
- 工具注册: 使用
addTool方法注册功能,每个工具需指定名称、描述、参数类型和执行逻辑 - 验证层: 使用 Zod 架构对输入参数进行验证,确保数据符合预期格式
- 执行流: 接收请求 → 验证参数 → 执行对应工具 → 返回结果
- 错误处理: 统一的错误捕获和格式化机制,确保稳定性
在本项目中的应用
在 TinyURL MCP 中,FastMCP 负责:
- 提供一个稳定的服务架构
- 处理工具注册和调用逻辑
- 确保参数验证和类型安全
- 管理服务生命周期
使用方法
前提条件
使用前,你需要:
- 在 TinyURL 官网获取 API 密钥
- 创建
.env文件并设置TINYURL_API_KEY环境变量
TINYURL_API_KEY=xxxxxx
实现
import { z } from "zod"
import { FastMCP } from "fastmcp";
import 'dotenv/config'
// Configure logging (using console in TypeScript)
const logger = {
info: (message: string) => console.info(`${new Date().toISOString()} - INFO - ${message}`),
error: (message: string) => console.error(`${new Date().toISOString()} - ERROR - ${message}`)
};
function getApiKey (): string {
const apiKey = process.env.TINYURL_API_KEY;
if (!apiKey) {
throw new Error('TINYURL_API_KEY environment variable must be set');
}
return apiKey;
}
const server = new FastMCP({
name: "TinyURL MCP",
version: "1.0.0",
});
// Add create_short_url tool
server.addTool({
name: "create_short_url",
description: "Convert a long URL to a short link",
parameters: z.object({
url: z.string().describe("URL to be shortened"),
}),
execute: async (args) => {
try {
const apiKey = getApiKey();
const endpoint = `https://api.tinyurl.com/create`;
// Prepare request parameters
const payload = { url: args.url };
// Set request headers
const headers = {
"accept": "application/json",
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
};
// Send API request
const response = await fetch(endpoint, {
method: 'POST',
headers: headers,
body: JSON.stringify(payload),
});
if (!response.ok) {
throw new Error(`Request failed with status: ${response.status}`);
}
// Return API response
const data = await response.json();
return JSON.stringify(data);
} catch (error) {
if (error instanceof Error) {
logger.error(`Error creating short URL: ${error.message}`);
return JSON.stringify({ error: `Unable to create short link: ${error.message}` });
}
logger.error(`Unknown error creating short URL`);
return JSON.stringify({ error: "Unknown error occurred while creating short link" });
}
}
});
function main () {
try {
// Validate API key
getApiKey();
// Start the server
logger.info("Starting TinyURL MCP service...");
server.start({
transportType: "stdio",
});
} catch (error) {
if (error instanceof Error) {
logger.error(`Failed to start TinyURL MCP service: ${error.message}`);
} else {
logger.error("Failed to start TinyURL MCP service with unknown error");
}
}
}
main();
本地测试
我们利用 MCP Inspector 工具来测试我们的 MCP 服务,运行如下命令:
npx @modelcontextprotocol/inspector pnpm start
浏览器打开:http://127.0.0.1:6274/#resources
我们以 modelcontextprotocol.io/introductio… 为例,
响应格式:
{
"data": {
"domain": "tinyurl.com",
"alias": "xxxx",
"deleted": false,
"archived": false,
"analytics": {
"enabled": true,
"public": false
},
"tags": [],
"created_at": "xxxxx",
"expires_at": null,
"tiny_url": "https://tinyurl.com/xxxxx",
"url": "https://modelcontextprotocol.io/introduction"
},
"code": 0,
"errors": []
}
如图:
扩展性
该项目基于 FastMCP 框架构建,你可以轻松扩展更多功能,例如:
- 添加获取链接统计数据的功能
- 实现自定义短链接别名
- 添加链接过期时间设置
总结
TinyURL MCP 展示了如何通过 Model Connector Protocol 实现第三方 API 的简洁封装。这种模式不仅使得 API 的使用更加便捷,还提供了类型安全和统一的错误处理,非常适合构建现代应用中的微服务组件。
注: 实践过程请确保遵循 TinyURL 的服务条款和使用政策。