Quick Start

1. Get Your API Key

Sign up for a free AgentKey account and get your API credentials:

  1. Visit AgentKey Dashboard
  2. Create your organization
  3. Copy your Client ID and Secret from the dashboard

2. Install the SDK

Choose your preferred integration method:

npm install @agentkey/sdk-react

3. Set Up Your Backend

First, create a link token endpoint in your backend:

// POST /api/link-token
app.post('/api/link-token', async (req, res) => {
  const response = await fetch('http://localhost:4000/api/link-token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-client-id': req.headers['x-client-id'], // Forward client credentials
      'x-client-secret': req.headers['x-client-secret'],
    },
    body: JSON.stringify({
      clientUserId: req.body.clientUserId, // Your user's ID
      providerId: req.body.providerId, // Optional: specific provider
    }),
  });
  
  const data = await response.json();
  res.json({ linkToken: data.linkToken });
});

// POST /api/connections/public_token/exchange
app.post('/api/connections/public_token/exchange', async (req, res) => {
  const response = await fetch('http://localhost:4000/api/connections/public_token/exchange', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-client-id': req.headers['x-client-id'],
      'x-client-secret': req.headers['x-client-secret'],
    },
    body: JSON.stringify({
      publicToken: req.body.publicToken,
    }),
  });
  
  const data = await response.json();
  res.json(data);
});

// POST /api/agent-requests
app.post('/api/agent-requests', async (req, res) => {
  const response = await fetch('http://localhost:4000/api/agent-requests', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-client-id': req.headers['x-client-id'],
      'x-client-secret': req.headers['x-client-secret'],
    },
    body: JSON.stringify(req.body),
  });
  
  const data = await response.json();
  res.json(data);
});

4. Add the React SDK

Implement the AgentKey connect flow in your React app:

import { AgentLinkError, AgentLinkMetadata, useAgentLink } from '@agentkey/sdk-react';
import { useEffect, useState } from 'react';

function ConnectWidget() {
  const [linkToken, setLinkToken] = useState<string | null>(null);
  const [publicToken, setPublicToken] = useState<string | null>(null);
  const [accessToken, setAccessToken] = useState<string | null>(null);

  // Fetch link token from your backend
  useEffect(() => {
    async function fetchLinkToken() {
      const res = await fetch('/api/link-token', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-client-id': import.meta.env.VITE_CLIENT_ID,
          'x-client-secret': import.meta.env.VITE_CLIENT_SECRET,
        },
        body: JSON.stringify({
          clientUserId: 'your-user-id',
          providerId: 'd3982096-ce7d-4f46-ae53-714b3e6304d2' // LinkedIn
        }),
      });
      const data = await res.json();
      setLinkToken(data.linkToken);
    }
    fetchLinkToken();
  }, []);

  // Exchange public token for access token
  const exchangePublicToken = async (publicToken: string) => {
    const res = await fetch('/api/connections/public_token/exchange', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-client-id': import.meta.env.VITE_CLIENT_ID,
        'x-client-secret': import.meta.env.VITE_CLIENT_SECRET,
      },
      body: JSON.stringify({ publicToken }),
    });
    
    const data = await res.json();
    setAccessToken(data.access_token);
  };

  const { open, ready, error } = useAgentLink({
    linkToken: linkToken || '',
    backendUrl: 'http://localhost:4000',
    onSuccess: (publicToken: string, metadata: AgentLinkMetadata) => {
      console.log('✅ Connected successfully!', { publicToken, metadata });
      setPublicToken(publicToken);
      
      // Exchange for access token
      exchangePublicToken(publicToken);
    },
    onError: (error: AgentLinkError) => {
      console.error('❌ Connection failed:', error);
    },
    env: 'sandbox', // or 'production'
  });

  return (
    <div>
      <button 
        onClick={open} 
        disabled={!ready}
        style={{
          padding: '12px 24px',
          backgroundColor: ready ? '#007bff' : '#ccc',
          color: 'white',
          border: 'none',
          borderRadius: '6px',
          cursor: ready ? 'pointer' : 'not-allowed',
        }}
      >
        {ready ? 'Connect Account' : 'Loading...'}
      </button>
      
      {publicToken && <p>✅ Public Token: {publicToken.substring(0, 20)}...</p>}
      {accessToken && <p>✅ Access Token: {accessToken.substring(0, 20)}...</p>}
    </div>
  );
}

Quick Agent Execution

Once you have an access token from the connection flow above, you can trigger agent actions. For detailed documentation on executions, see our Agent Executions guide.

const executeAgent = async (accessToken: string) => {
  const response = await fetch('/api/agent-requests', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-client-id': 'your-client-id',
      'x-client-secret': 'your-client-secret',
    },
    body: JSON.stringify({
      accessToken: accessToken,
      action: 'Extract LinkedIn profile information',
      startingUrl: 'https://www.linkedin.com/in/sagar-jaiswall/',
      parameters: {},
      responseFormat: {
        jobs: [
          {
            company: 'string - Company name',
            jobTitle: 'string - Position title',
            dates: 'string - Employment period'
          }
        ],
        totalJobs: 'number - Total jobs found'
      }
    }),
  });
  
  const data = await response.json();
  console.log('Execution started:', data.requestId);
};

Authentication Flow

The complete authentication flow works as follows:

  1. Create Link Token: Your backend requests a link token from AgentKey
  2. User Authentication: User authenticates with the provider (LinkedIn, GitHub, etc.)
  3. Public Token: AgentKey returns a public token after successful authentication
  4. Token Exchange: Your backend exchanges the public token for an access token
  5. Agent Actions: Use the access token to trigger agent actions

Environment Configuration

Set up your environment variables:

# Frontend (.env.local)
VITE_CLIENT_ID=your_client_id
VITE_CLIENT_SECRET=your_client_secret

# Backend (.env)
AGENTKEY_CLIENT_ID=your_client_id
AGENTKEY_CLIENT_SECRET=your_client_secret
AGENTKEY_BACKEND_URL=http://localhost:4000

What’s Next?

Explore Use Cases

Check Out Examples

Configure Your Environment

Support

Need help getting started?


Ready to build? Start with our React example or dive into the API reference.