Loading...
Request your first delegated access token and call a third-party API.
Install the Cred SDK:
npm install @credninja/sdkOr for Python: pip install cred-auth
From your Cred developer dashboard, you need:
# Add to your .env file
CRED_APP_CLIENT_ID=your_app_client_id
CRED_AGENT_TOKEN=cred_at_...Initialize the client with your credentials:
import { Cred, ConsentRequiredError } from '@credninja/sdk';
const cred = new Cred({
agentToken: process.env.CRED_AGENT_TOKEN,
appClientId: process.env.CRED_APP_CLIENT_ID,
baseUrl: 'https://api.cred.ninja',
});Call delegate() with the user ID, service, and scopes:
async function getCalendarEvents(userId: string) {
try {
// Request delegated access to Google Calendar
const { accessToken } = await cred.delegate({
userId,
service: 'google',
scopes: ['calendar.readonly'],
});
// Use the token directly with Google API
const response = await fetch(
'https://www.googleapis.com/calendar/v3/calendars/primary/events',
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
return response.json();
} catch (error) {
if (error instanceof ConsentRequiredError) {
// User hasn't authorized yet
// Redirect them to the consent URL
console.log('Redirect user to:', error.consentUrl);
return null;
}
throw error;
}
}The first time you request delegation for a user, they need to authorize your app:
// In your web app
app.get('/connect/google', async (req, res) => {
try {
await cred.delegate({
userId: req.user.id,
service: 'google',
scopes: ['calendar.readonly'],
});
// Already authorized, proceed
res.redirect('/dashboard');
} catch (error) {
if (error instanceof ConsentRequiredError) {
// Redirect to Cred consent page
res.redirect(error.consentUrl);
}
}
});
// After user approves, they're redirected back
app.get('/callback', async (req, res) => {
// Now delegation will succeed
const { accessToken } = await cred.delegate({
userId: req.user.id,
service: 'google',
scopes: ['calendar.readonly'],
});
// Use the token...
});When you called cred.delegate(), Cred’s 7-step pipeline executed:
Install the Cred MCP server for interactive credential delegation:
{
"mcpServers": {
"cred": {
"command": "npx",
"args": ["-y", "@credninja/mcp"],
"env": {
"CRED_AGENT_TOKEN": "cred_at_...",
"CRED_APP_CLIENT_ID": "your_app_client_id"
}
}
}
}The MCP server provides 4 tools: cred_delegate, cred_use, cred_status, and cred_revoke.