@osiris-ai/discord-sdk
Version:
Osiris Discord SDK
245 lines (185 loc) • 7.3 kB
Markdown
# @osiris-ai/discord-sdk
OAuth 2.0 Discord authenticator for building authenticated MCPs with Discord integration.
[](https://badge.fury.io/js/@osiris-ai%2Fdiscord-sdk)
[](https://opensource.org/licenses/MIT)
## Overview
The Discord SDK provides seamless OAuth 2.0 authentication for Discord in the [Osiris](https://docs.osirislabs.xyz) ecosystem. Build powerful MCPs (Model Context Protocol) that can interact with Discord servers, channels, and users with enterprise-grade security and zero-configuration authentication.
**Key Features:**
- 🔐 **Zero-config OAuth** - No client credentials or setup required
- 🤖 **Bot & User Auth** - Support for both Discord bot and user authentication
- 🏰 **Guild Management** - Full Discord server integration capabilities
- 🔄 **Auto Token Refresh** - Automatic token lifecycle management
- 🛡️ **Enterprise Security** - Built on Osiris Hub authentication
- 📝 **Full TypeScript** - Complete type safety and IDE support
## Installation
```bash
npm install @osiris-ai/discord-sdk @osiris-ai/sdk
```
## Quick Start
### Hub Authentication (Recommended)
The Discord authenticator works automatically through the Osiris Hub - no Discord client setup required.
```typescript
import { createMcpServer, getAuthContext } from '@osiris-ai/sdk';
import { createSuccessResponse, createErrorResponse } from '../utils/types.js';
import { z } from 'zod';
await createMcpServer({
name: 'discord-mcp',
version: '1.0.0',
auth: {
useHub: true,
hubConfig: {
baseUrl: process.env.HUB_BASE_URL!,
clientId: process.env.OAUTH_CLIENT_ID!,
clientSecret: process.env.OAUTH_CLIENT_SECRET!,
}
},
configure: (server) => {
// Send Discord message
server.tool(
'send_discord_message',
'Send a message to a Discord channel',
{
channelId: z.string(),
content: z.string(),
useBot: z.boolean().optional()
},
async ({ channelId, content, useBot = false }) => {
try {
const { token, context } = getAuthContext("osiris");
if (!token || !context) {
return createErrorResponse("User not authenticated");
}
// Send message through Hub action API
const response = await fetch(`https://api.osirislabs.xyz/v1/hub/action/${context.deploymentId}/discord`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token.access_token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
method: 'POST',
url: `/channels/${channelId}/messages`,
data: { content, useBot }
})
});
const result = await response.json();
return createSuccessResponse('Message sent successfully', result);
} catch (error) {
return createErrorResponse(error);
}
}
);
}
});
```
### Available Discord Scopes
Configure your MCP to request specific Discord permissions:
All slack scopes are supported and they all need to prefixed with `discord:`
## Local Authentication (Advanced)
For custom authentication flows or enterprise requirements:
```typescript
import { DiscordAuthenticator } from '@osiris-ai/discord-sdk';
import { createMcpServer } from '@osiris-ai/sdk';
const discordAuth = new DiscordAuthenticator(
['bot', 'guilds', 'messages.read', 'messages.write'],
{
clientId: process.env.DISCORD_CLIENT_ID!,
clientSecret: process.env.DISCORD_CLIENT_SECRET!,
redirectUri: 'http://localhost:3000/discord/callback'
}
);
await createMcpServer({
name: 'discord-mcp',
version: '1.0.0',
auth: {
useHub: false,
directAuth: {
discord: discordAuth
}
},
configure: (server) => {
// Your Discord tools here
}
});
```
## API Reference
### DiscordAuthenticator
The main authenticator class for Discord OAuth integration.
```typescript
class DiscordAuthenticator extends OAuthAuthenticator<DiscordCallbackParams, DiscordTokenResponse>
```
#### Constructor
```typescript
new DiscordAuthenticator(allowedScopes: string[], config: DiscordAuthenticatorConfig)
```
**Parameters:**
- `allowedScopes`: Array of Discord OAuth scopes your MCP requires
- `config`: Discord application configuration
#### Methods
##### `getAuthenticationURL(scopes: string[], options: AuthenticationURLOptions): string`
Generate Discord OAuth authorization URL.
##### `callback(params: DiscordCallbackParams): Promise<DiscordTokenResponse>`
Handle OAuth callback and exchange code for tokens.
##### `refreshToken(refreshToken: string): Promise<DiscordTokenResponse>`
Refresh an expired access token.
##### `getUserInfo(accessToken: string): Promise<DiscordUserInfo>`
Get authenticated user information.
##### `action(params: ActionParams, accessToken: string, refreshToken?: string): Promise<ActionResponse>`
Execute Discord API actions with automatic token refresh.
## Error Handling
The Discord authenticator provides robust error handling with automatic retries and rate limiting:
```typescript
server.tool('resilient_discord_tool', 'Discord tool with error handling', schema, async (params) => {
try {
const { token, context } = getAuthContext("osiris");
if (!token || !context) {
return createErrorResponse("🔐 Please connect your Discord account first");
}
// Discord API call with automatic error handling
const response = await fetch(`https://api.osirislabs.xyz/v1/hub/action/${context.deploymentId}/discord/users/@me/guilds`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token.access_token}`,
'Content-Type': 'application/json'
}
});
if (response.status === 429) {
const retryAfter = response.headers.get('retry-after');
return createErrorResponse(`Rate limited. Please try again in ${retryAfter} seconds.`);
}
const guilds = await response.json();
return createSuccessResponse('Discord servers retrieved', guilds);
} catch (error) {
return createErrorResponse(`Discord error: ${error.message}`);
}
});
```
## Getting Started
1. **Install the Osiris CLI:**
```bash
npm install -g @osiris-ai/cli
```
2. **Set up authentication:**
```bash
npx @osiris-ai/cli register
npx @osiris-ai/cli create-client
npx @osiris-ai/cli connect-auth
```
3. **Create your Discord MCP:**
```bash
npx @osiris-ai/cli create-mcp my-discord-mcp
```
4. **Add Discord integration:**
```bash
npm install @osiris-ai/discord-sdk
```
## Contributing
We welcome contributions! Please see our [Contributing Guide](https://github.com/fetcchx/osiris-ai/blob/main/CONTRIBUTING.md) for details.
## Support
- **Documentation:** [https://docs.osirislabs.xyz](https://docs.osirislabs.xyz)
- **GitHub Issues:** [https://github.com/fetcchx/osiris-ai/issues](https://github.com/fetcchx/osiris-ai/issues)
- **Discord Community:** [Join our Discord](https://discord.osirislabs.xyz)
## License
MIT License - see [LICENSE](LICENSE) file for details.
---
Built with ❤️ by the [Osiris Labs](https://osirislabs.xyz) team.