linkedin-mcp-server

linkedin-mcp-server

MCP server for LinkedIn API integration. Enables authentication, profile access, connections, search, messaging, and feed management via OAuth2.

Category
访问服务器

README

LinkedIn MCP Server

A Model Context Protocol (MCP) server implementation that provides seamless integration with LinkedIn's API. This server enables applications to authenticate, access LinkedIn data, and perform various operations through the MCP interface.

🌟 Features

  • OAuth2 Authentication: Secure LinkedIn OAuth2 flow with PKCE support
  • User Profile Access: Retrieve authenticated user profile information
  • Connections Management: List and manage user connections
  • Search Functionality: Search for people on LinkedIn
  • Feed Management: Access and interact with user feed
  • Messaging: Send direct messages to connections
  • Skills & Recommendations: Access skills and recommendations data
  • Token Management: Automatic token refresh and validation
  • Rate Limiting: Built-in rate limiting to respect API quotas
  • Error Handling: Comprehensive error handling with detailed messages
  • Logging: Winston-based logging for debugging and monitoring
  • Security: CSRF protection, HTTPS support, secure credential storage

📋 Prerequisites

  • Node.js 16.0.0 or higher
  • npm 8.0.0 or higher
  • LinkedIn Developer Account
  • LinkedIn App credentials (Client ID, Client Secret)

🚀 Installation

1. Clone the Repository

git clone https://github.com/yourusername/linkedin_mcp_server.git
cd linkedin_mcp_server

2. Install Dependencies

npm install

3. Configure Environment Variables

Create a .env file in the root directory with your LinkedIn credentials:

# LinkedIn OAuth Configuration
LINKEDIN_CLIENT_ID=your_client_id_here
LINKEDIN_CLIENT_SECRET=your_client_secret_here
LINKEDIN_REDIRECT_URI=http://localhost:3000/callback

# Server Configuration
PORT=3000
HOST=localhost
NODE_ENV=development

# Optional: Anthropic/OpenAI API Keys
CLAUDE_API_KEY=your_claude_api_key
OPENAI_API_KEY=your_openai_api_key

4. Get LinkedIn Credentials

  1. Visit LinkedIn Developers
  2. Create a new app
  3. Copy your Client ID and Client Secret
  4. Add your redirect URI (default: http://localhost:3000/callback)
  5. Request access to required API endpoints

🔧 Configuration

Environment Variables

See .env file for all available configuration options:

Variable Description Default
LINKEDIN_CLIENT_ID LinkedIn OAuth Client ID Required
LINKEDIN_CLIENT_SECRET LinkedIn OAuth Client Secret Required
LINKEDIN_REDIRECT_URI OAuth callback URI http://localhost:3000/callback
PORT Server port 3000
NODE_ENV Environment (dev/prod) development
RATE_LIMIT_PER_MINUTE API rate limit 60
LOG_LEVEL Logging level info

📝 Usage

Starting the Server

Development Mode (with auto-reload):

npm run dev

Production Mode:

npm start

OAuth Authentication Flow

1. Get Authorization URL

import LinkedInOAuth from './src/oauth.js';

const oauth = new LinkedInOAuth(
  process.env.LINKEDIN_CLIENT_ID,
  process.env.LINKEDIN_CLIENT_SECRET,
  process.env.LINKEDIN_REDIRECT_URI
);

const authUrl = oauth.getAuthorizationUrl();
console.log('Visit:', authUrl);

2. Handle Callback

// After user authorizes, LinkedIn redirects with 'code' and 'state'
const token = await oauth.exchangeCodeForToken(code, state);
console.log('Access Token:', token.accessToken);

3. Use Access Token

import LinkedInClient from './src/linkedin.js';

const client = new LinkedInClient(token.accessToken);
const profile = await client.getProfile();
console.log('User Profile:', profile);

📚 API Documentation

LinkedInClient Methods

Profile Operations

// Get authenticated user's profile
const profile = await client.getProfile();

// Get specific user's profile
const userProfile = await client.getUserProfile(userId);

// Get user's email
const email = await client.getEmail();

Connections

// Get user's connections (paginated)
const connections = await client.getConnections(start = 0, count = 10);

Search

// Search for people
const results = await client.searchPeople('software engineer', count = 10);

Social Features

// Get user's skills
const skills = await client.getSkills();

// Get received recommendations
const recommendations = await client.getRecommendations();

// Get job experience
const experience = await client.getExperience();

// Get user's feed
const feed = await client.getFeed(count = 10);

Messaging

// Send a message to a connection
const result = await client.sendMessage(recipientId, 'Hello!');

Posting

// Create a share (post)
const share = await client.createShare('This is my new post!', 'TEXT_ONLY');

LinkedInOAuth Methods

// Get authorization URL
const authUrl = oauth.getAuthorizationUrl();

// Exchange authorization code for token
const token = await oauth.exchangeCodeForToken(code, state);

// Refresh an access token
const newToken = await oauth.refreshAccessToken(refreshToken);

// Revoke a token
await oauth.revokeToken(accessToken);

// Validate token
const validation = await oauth.validateToken(accessToken);

// Get user info
const userInfo = await oauth.getUserInfo(accessToken);

🧪 Testing

Run all tests:

npm test

Run tests in watch mode:

npm run test:watch

Generate coverage report:

npm run test:coverage

🔍 Code Quality

Linting

# Check code style
npm run lint

# Fix linting issues
npm run lint:fix

Formatting

# Format code with Prettier
npm run format

# Check formatting
npm run format:check

📂 Project Structure

linkedin_mcp_server/
├── src/
│   ├── index.js           # Server entry point
│   ├── linkedin.js        # LinkedIn API client
│   ├── oauth.js           # OAuth2 implementation
│   └── ...
├── tests/
│   ├── linkedin.test.js
│   └── oauth.test.js
├── .env                   # Environment configuration
├── .gitignore            # Git ignore rules
├── package.json          # Project dependencies
└── README.md             # This file

🔐 Security Considerations

  1. Never commit .env file - Contains sensitive credentials
  2. Use HTTPS in production - Set USE_HTTPS=true and provide SSL certificates
  3. Validate state parameter - CSRF protection in OAuth flow
  4. Store tokens securely - Use environment variables or secure storage
  5. Implement rate limiting - Configured via RATE_LIMIT_PER_MINUTE
  6. Refresh tokens regularly - Call refreshAccessToken() before expiration
  7. Use PKCE flow - Enable with usePKCE: true in OAuth methods

🐛 Troubleshooting

Common Issues

Issue: "Invalid client credentials"

  • Verify LINKEDIN_CLIENT_ID and LINKEDIN_CLIENT_SECRET are correct
  • Check credentials in LinkedIn Developer Portal

Issue: "Redirect URI mismatch"

  • Ensure LINKEDIN_REDIRECT_URI matches app configuration in LinkedIn Developer Portal
  • URIs are case-sensitive

Issue: "Token expired"

  • Call refreshAccessToken() with refresh token
  • Implement automatic token refresh before expiration

Issue: "Rate limit exceeded"

  • Reduce request frequency
  • Increase RATE_LIMIT_PER_MINUTE in .env
  • Implement exponential backoff

📦 Dependencies

Core Dependencies

  • express: Web framework
  • node-fetch: HTTP requests
  • jsonwebtoken: JWT handling
  • dotenv: Environment variables
  • axios: HTTP client
  • winston: Logging
  • helmet: Security headers
  • cors: CORS handling

Dev Dependencies

  • jest: Testing framework
  • eslint: Code linting
  • prettier: Code formatting
  • nodemon: Development auto-reload

📖 Examples

Basic Usage Example

import LinkedInOAuth from './src/oauth.js';
import LinkedInClient from './src/linkedin.js';
import 'dotenv/config';

async function main() {
  // Initialize OAuth
  const oauth = new LinkedInOAuth(
    process.env.LINKEDIN_CLIENT_ID,
    process.env.LINKEDIN_CLIENT_SECRET,
    process.env.LINKEDIN_REDIRECT_URI
  );

  // Get authorization URL
  const authUrl = oauth.getAuthorizationUrl();
  console.log('Please visit:', authUrl);

  // After user authorizes, exchange code for token
  const token = await oauth.exchangeCodeForToken(code, state);
  
  // Initialize client with access token
  const client = new LinkedInClient(token.accessToken);

  // Fetch profile
  const profile = await client.getProfile();
  console.log('Profile:', profile);

  // Get connections
  const connections = await client.getConnections(0, 10);
  console.log('Connections:', connections);

  // Search for people
  const searchResults = await client.searchPeople('AI Engineer', 5);
  console.log('Search Results:', searchResults);
}

main().catch(console.error);

Express Integration

import express from 'express';
import LinkedInOAuth from './src/oauth.js';
import LinkedInClient from './src/linkedin.js';

const app = express();
const oauth = new LinkedInOAuth(
  process.env.LINKEDIN_CLIENT_ID,
  process.env.LINKEDIN_CLIENT_SECRET,
  process.env.LINKEDIN_REDIRECT_URI
);

// Redirect to LinkedIn login
app.get('/login', (req, res) => {
  const authUrl = oauth.getAuthorizationUrl();
  res.redirect(authUrl);
});

// Handle OAuth callback
app.get('/callback', async (req, res) => {
  const { code, state } = req.query;
  
  try {
    const token = await oauth.exchangeCodeForToken(code, state);
    req.session.token = token;
    res.redirect('/dashboard');
  } catch (error) {
    res.status(400).send('Authentication failed');
  }
});

// Protected route
app.get('/dashboard', async (req, res) => {
  const client = new LinkedInClient(req.session.token.accessToken);
  const profile = await client.getProfile();
  res.json(profile);
});

app.listen(3000, () => console.log('Server running on :3000'));

🤝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit changes (git commit -m 'Add AmazingFeature')
  4. Push to branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Development Guidelines

  • Write tests for new features
  • Follow ESLint and Prettier rules
  • Update documentation
  • Add comments for complex logic

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🔗 Links

📧 Support

For issues, questions, or suggestions:

🙏 Acknowledgments

  • LinkedIn API Documentation
  • MCP Community
  • Contributors and testers

Last Updated: 2024 Version: 1.0.0 Status: Active Development

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选