npm package: @osiris-ai/github-sdk
Description: Osiris GitHub SDK
Latest version: 0.1.1

# @osiris-ai/github-sdk

OAuth 2.0 GitHub authenticator for building authenticated MCPs with GitHub integration.

[![npm version](https://badge.fury.io/js/@osiris-ai%2Fgithub-sdk.svg)](https://badge.fury.io/js/@osiris-ai%2Fgithub-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Overview

The GitHub SDK provides seamless OAuth 2.0 authentication for GitHub in the [Osiris](https://docs.osirislabs.xyz) ecosystem. Build powerful MCPs (Model Context Protocol) that can interact with GitHub repositories, issues, pull requests, and more with enterprise-grade security and zero-configuration authentication.

**Key Features:**
- 🔐 **Zero-config OAuth** - No client credentials or setup required
- 📚 **Full GitHub API** - Complete access to repositories, issues, PRs, and more
- 🔄 **Auto Token Refresh** - Automatic token lifecycle management
- 🛡️ **Enterprise Security** - Built on Osiris Hub authentication
- 📝 **Full TypeScript** - Complete type safety with Octokit integration
- ⚡ **Octokit Integration** - Familiar GitHub API interface

## Installation

```bash
npm install @osiris-ai/github-sdk @osiris-ai/sdk
```

## Quick Start

### Hub Authentication (Recommended)

The GitHub authenticator works automatically through the Osiris Hub - no GitHub OAuth app setup required.

```typescript
import { createMcpServer, getAuthContext } from '@osiris-ai/sdk';
import { createHubGitHubClient } from '@osiris-ai/github-sdk';
import { createSuccessResponse, createErrorResponse } from '../utils/types.js';
import { z } from 'zod';

await createMcpServer({
  name: 'github-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) => {
    // Create GitHub issue
    server.tool(
      'create_github_issue',
      'Create a new GitHub issue',
      {
        owner: z.string(),
        repo: z.string(),
        title: z.string(),
        body: z.string(),
        labels: z.array(z.string()).optional()
      },
      async ({ owner, repo, title, body, labels }) => {
        try {
          const { token, context } = getAuthContext("osiris");
          if (!token || !context) {
            return createErrorResponse("User not authenticated");
          }

          // Create authenticated GitHub client
          const github = createHubGitHubClient({
            hubBaseUrl: process.env.HUB_BASE_URL!,
            token: token,
            context: context
          });

          // Create issue using Octokit interface
          const issue = await github.rest.issues.create({
            owner,
            repo,
            title,
            body,
            labels
          });

          return createSuccessResponse('Issue created successfully', {
            issueNumber: issue.data.number,
            issueUrl: issue.data.html_url,
            issueId: issue.data.id
          });
        } catch (error) {
          return createErrorResponse(error);
        }
      }
    );
  }
});
```

### Available GitHub Scopes

Configure your MCP to request specific GitHub permissions:

All slack scopes are supported and they all need to prefixed with `github:`

## Local Authentication (Advanced)

For custom authentication flows or enterprise requirements:

```typescript
import { GitHubAuthenticator } from '@osiris-ai/github-sdk';
import { createMcpServer } from '@osiris-ai/sdk';

const githubAuth = new GitHubAuthenticator(
  ['repo', 'user:email', 'issues:write'],
  {
    clientId: process.env.GITHUB_CLIENT_ID!,
    clientSecret: process.env.GITHUB_CLIENT_SECRET!,
    redirectUri: 'http://localhost:3000/github/callback'
  }
);

await createMcpServer({
  name: 'github-mcp',
  version: '1.0.0',
  auth: {
    useHub: false,
    directAuth: {
      github: githubAuth
    }
  },
  configure: (server) => {
    // Your GitHub tools here
  }
});
```

## API Reference

### GitHubAuthenticator

The main authenticator class for GitHub OAuth integration.

```typescript
class GitHubAuthenticator extends OAuthAuthenticator<GitHubCallbackParams, GitHubTokenResponse>
```

#### Constructor

```typescript
new GitHubAuthenticator(allowedScopes: string[], config: GitHubAuthenticatorConfig)
```

**Parameters:**
- `allowedScopes`: Array of GitHub OAuth scopes your MCP requires
- `config`: GitHub OAuth application configuration

#### Methods

##### `getAuthenticationURL(scopes: string[], options: AuthenticationURLOptions): string`

Generate GitHub OAuth authorization URL.

##### `callback(params: GitHubCallbackParams): Promise<GitHubTokenResponse>`

Handle OAuth callback and exchange code for tokens.

##### `refreshToken(refreshToken: string): Promise<GitHubTokenResponse>`

Refresh an expired access token.

##### `getUserInfo(accessToken: string): Promise<GitHubUserInfo>`

Get authenticated user information.

##### `action(params: ActionParams, accessToken: string, refreshToken?: string): Promise<ActionResponse>`

Execute GitHub API actions with automatic token refresh.

### HubGitHubClient

GitHub client that routes requests through the Osiris Hub with full Octokit compatibility.

```typescript
class HubGitHubClient
```

#### Methods

##### `rest: RestEndpointMethods`

Access to the full GitHub REST API through Octokit interface.

##### `request(endpoint: string, options?: any): Promise<OctokitResponse<any, any>>`

Make direct GitHub API requests.

##### `getAuthStatus(): AuthStatus`

Get current authentication status and debugging information.

### createHubGitHubClient

Factory function to create Hub-authenticated GitHub client.

```typescript
function createHubGitHubClient(config: GitHubClientConfig): HubGitHubClient
```

## Usage Examples

### Repository Management

```typescript
server.tool(
  'list_repos',
  'List user repositories',
  { type: z.enum(['all', 'public', 'private']).default('all') },
  async ({ type }) => {
    const { token, context } = getAuthContext("osiris");
    if (!token || !context) {
      return createErrorResponse("User not authenticated");
    }

    const github = createHubGitHubClient({
      hubBaseUrl: process.env.HUB_BASE_URL!,
      token: token,
      context: context
    });

    const repos = await github.rest.repos.listForAuthenticatedUser({
      type,
      sort: 'updated',
      per_page: 30
    });

    return createSuccessResponse('Repositories retrieved', {
      repositories: repos.data.map(repo => ({
        name: repo.name,
        fullName: repo.full_name,
        url: repo.html_url,
        private: repo.private,
        language: repo.language
      }))
    });
  }
);
```

## Error Handling

The GitHub authenticator provides robust error handling with automatic retries and detailed error messages:

```typescript
server.tool('resilient_github_tool', 'GitHub tool with error handling', schema, async (params) => {
  try {
    const { token, context } = getAuthContext("osiris");
    if (!token || !context) {
      return createErrorResponse("🔐 Please connect your GitHub account first");
    }

    const github = createHubGitHubClient({
      hubBaseUrl: process.env.HUB_BASE_URL!,
      token: token,
      context: context
    });

    // GitHub API call with automatic error handling
    const result = await github.rest.repos.listForAuthenticatedUser();
    return createSuccessResponse('GitHub repositories retrieved', result.data);
  } catch (error: any) {
    if (error.status === 401) {
      return createErrorResponse("❌ GitHub authentication expired. Please reconnect your account.");
    }
    if (error.status === 403) {
      return createErrorResponse("❌ Insufficient GitHub permissions. Please grant additional scopes.");
    }
    if (error.status === 404) {
      return createErrorResponse("❌ GitHub resource not found. Check repository name and permissions.");
    }
    return createErrorResponse(`GitHub 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 GitHub MCP:**
   ```bash
   npx @osiris-ai/cli create-mcp my-github-mcp
   ```

4. **Add GitHub integration:**
   ```bash
   npm install @osiris-ai/github-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.