Skip to main content
Glama
AlyssonM

HiveAuth MCP Server

by AlyssonM

derive_credential

Create privacy-preserving verifiable credentials by selectively disclosing specific attributes from original credentials using JSON-LD frames and zero-knowledge proofs.

Instructions

Derive credentials with selective disclosure using JSON-LD frames. Supports credential chaining and zero-knowledge proofs for privacy-preserving presentations.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
originalCredentialYesW3C Verifiable Credential
frameYesJSON-LD frame for selective disclosure
nonceNoNonce for derived proof

Implementation Reference

  • Core handler implementation for 'derive_credential' tool. Validates input using DeriveCredentialInputSchema, calls HiveAuth API (/api/derive) with originalCredential and frame for selective disclosure derivation, performs field analysis for privacy summary, generates detailed markdown+JSON output, and falls back to simulation mode if API unavailable.
    export async function deriveCredential(args: any): Promise<CallToolResult> {
      // Validate and sanitize input
      const validation = validateAndSanitizeInput(DeriveCredentialInputSchema, args, 'derive_credential');
      
      if (!validation.success) {
        return createValidationErrorResult(validation.error!);
      }
    
      const data = validation.data!;
      const { originalCredential, frame, nonce } = data;
    
      const HIVEAUTH_API_BASE_URL = process.env.HIVEAUTH_API_BASE_URL || 'http://localhost:3000';
      const DERIVE_ENDPOINT = `${HIVEAUTH_API_BASE_URL}/api/derive`;
    
      try {
        console.log(`[DeriveCredential] Starting credential derivation for credential: ${originalCredential.id}`);
    
        const payload = {
          credential: originalCredential,
          frame,
          ...(nonce && { nonce })
        };
    
        const response = await fetch(DERIVE_ENDPOINT, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(payload),
        });
    
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({ message: response.statusText }));
          throw new Error(`Failed to derive credential: ${errorData.message}`);
        }
    
        const result = await response.json();
    
        // Analyze the derivation
        const originalFields = extractCredentialFields(originalCredential);
        const derivedFields = extractCredentialFields(result.derivedCredential);
        const hiddenFields = originalFields.filter(field => !derivedFields.includes(field));
        const revealedFields = derivedFields;
    
        const summary = [
          `🔄 **Credential Derivation Results**`,
          ``,
          `• Original Credential ID: ${originalCredential.id || 'Not specified'}`,
          `• Derived Credential ID: ${result.derivedCredential?.id || 'Generated automatically'}`,
          `• Derivation Method: ${result.derivationMethod || 'JSON-LD Frame'}`,
          `• Selective Disclosure: ${hiddenFields.length > 0 ? 'Yes' : 'No'}`,
          ``,
          `**📊 Field Analysis:**`,
          `• Original Fields: ${originalFields.length}`,
          `• Revealed Fields: ${revealedFields.length}`,
          `• Hidden Fields: ${hiddenFields.length}`,
          `• Privacy Level: ${Math.round((hiddenFields.length / originalFields.length) * 100)}% fields hidden`,
          ``
        ];
    
        if (revealedFields.length > 0) {
          summary.push(`**✅ Revealed Fields (${revealedFields.length}):**`);
          revealedFields.forEach((field, index) => {
            summary.push(`${index + 1}. ${field}`);
          });
          summary.push(``);
        }
    
        if (hiddenFields.length > 0) {
          summary.push(`**🔒 Hidden Fields (${hiddenFields.length}):**`);
          hiddenFields.forEach((field, index) => {
            summary.push(`${index + 1}. ${field} (protected by selective disclosure)`);
          });
          summary.push(``);
        }
    
        // Proof information
        if (result.derivedCredential?.proof) {
          const proof = result.derivedCredential.proof;
          summary.push(`**🔐 Derived Proof Information:**`);
          summary.push(`• Proof Type: ${proof.type || 'Unknown'}`);
          summary.push(`• Verification Method: ${proof.verificationMethod || 'Not specified'}`);
          summary.push(`• Created: ${proof.created || 'Not specified'}`);
          summary.push(`• Purpose: ${proof.proofPurpose || 'assertionMethod'}`);
          
          if (nonce) {
            summary.push(`• Nonce: ${nonce} (replay protection enabled)`);
          }
          summary.push(``);
        }
    
        // Derivation integrity checks
        summary.push(`**🛡️ Integrity Verification:**`);
        summary.push(`• Original signature preserved: ${result.signaturePreserved ? '✅ Yes' : '❌ No'}`);
        summary.push(`• Derivation proof valid: ${result.derivationValid ? '✅ Yes' : '❌ No'}`);
        summary.push(`• JSON-LD frame applied: ${result.frameApplied ? '✅ Yes' : '❌ No'}`);
        
        if (result.chainedCredential) {
          summary.push(`• Credential chaining: ✅ Derived credential properly chained`);
        }
    
        // Usage recommendations
        summary.push(``);
        summary.push(`**💡 Usage Recommendations:**`);
        if (hiddenFields.length > 0) {
          summary.push(`• Use this derived credential for privacy-sensitive scenarios`);
          summary.push(`• Original credential remains unchanged and can be used separately`);
        }
        if (nonce) {
          summary.push(`• Nonce provides replay protection - credential is single-use`);
        }
        summary.push(`• Verify derived credential independently before accepting`);
        summary.push(`• Consider the revealed fields sufficient for your use case`);
    
        return {
          content: [
            {
              type: 'text',
              text: summary.join('\n')
            },
            {
              type: 'text',
              text: `\`\`\`json\n${JSON.stringify({
                derivationSummary: {
                  originalCredentialId: originalCredential.id,
                  derivedCredentialId: result.derivedCredential?.id,
                  originalFields: originalFields.length,
                  revealedFields: revealedFields.length,
                  hiddenFields: hiddenFields.length,
                  privacyLevel: Math.round((hiddenFields.length / originalFields.length) * 100),
                  frameApplied: result.frameApplied,
                  signaturePreserved: result.signaturePreserved
                },
                derivedCredential: result.derivedCredential,
                derivationProof: result.derivationProof
              }, null, 2)}\n\`\`\``
            }
          ]
        };
      } catch (error: any) {
        // Check if it's a network error (HiveAuth API not available)
        if (error.message.includes('fetch failed') || error.message.includes('ECONNREFUSED')) {
          return {
            content: [
              {
                type: 'text',
                text: `🔄 **Credential Derivation (Simulation Mode)**\n\n` +
                      `Since the HiveAuth API is not available, here's what the credential derivation would accomplish:\n\n` +
                      `**Input Analysis:**\n` +
                      `• Original Credential ID: ${originalCredential.id || 'Not specified'}\n` +
                      `• Original Credential Type: ${originalCredential.type?.join(', ') || 'Unknown'}\n` +
                      `• Derivation Frame: ${Object.keys(frame).length} frame properties specified\n` +
                      `• Nonce: ${nonce ? 'Provided (replay protection)' : 'Not provided'}\n\n` +
                      `**Expected Derivation Results:**\n` +
                      `• New credential with selective disclosure applied\n` +
                      `• Original signature preserved in derived proof\n` +
                      `• Only specified fields revealed according to frame\n` +
                      `• Cryptographic link to original credential maintained\n\n` +
                      `**Privacy Benefits:**\n` +
                      `• Sensitive fields hidden while maintaining verifiability\n` +
                      `• Zero-knowledge proof of credential possession\n` +
                      `• Granular control over revealed information\n\n` +
                      `**To enable full derivation:** Ensure HiveAuth API is running at ${HIVEAUTH_API_BASE_URL}`
              }
            ]
          };
        }
    
        return {
          content: [
            {
              type: 'text',
              text: `Failed to derive credential: ${error.message}`
            }
          ],
          isError: true
        };
      }
    }
  • Zod schema defining the input structure for derive_credential: requires originalCredential (CredentialSchema), frame (JSON-LD object), optional nonce (string for replay protection).
    export const DeriveCredentialInputSchema = z.object({
      originalCredential: CredentialSchema,
      frame: z.object({}).passthrough().describe('JSON-LD frame for selective disclosure'),
      nonce: z.string().optional().describe('Nonce for derived proof')
    });
  • MCP tool registration definition, mapping 'derive_credential' name to its description and input schema (converted to JSON Schema via zodToJsonSchema for MCP protocol compliance).
    {
      name: 'derive_credential',
      description: 'Derive credentials with selective disclosure using JSON-LD frames. Supports credential chaining and zero-knowledge proofs for privacy-preserving presentations.',
      inputSchema: TOOL_SCHEMAS.derive_credential
    },
  • src/index.ts:107-108 (registration)
    Runtime tool dispatch in main server switch statement, routing 'derive_credential' calls to the deriveCredential handler function.
    case 'derive_credential':
      return await deriveCredential(args);
  • Utility helper to recursively extract claim field paths from a credential (excluding metadata like @context, id, type, proof) for deriving revealed/hidden fields in derivation analysis.
    function extractCredentialFields(credential: any): string[] {
      const fields: string[] = [];
      
      function extractFromObject(obj: any, prefix = ''): void {
        if (!obj || typeof obj !== 'object') return;
        
        for (const [key, value] of Object.entries(obj)) {
          const fieldPath = prefix ? `${prefix}.${key}` : key;
          
          // Skip metadata fields
          if (['@context', 'id', 'type', 'proof'].includes(key)) continue;
          
          if (value && typeof value === 'object' && !Array.isArray(value)) {
            extractFromObject(value, fieldPath);
          } else {
            fields.push(fieldPath);
          }
        }
      }
      
      extractFromObject(credential);
      return fields;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'selective disclosure', 'credential chaining', and 'zero-knowledge proofs', which give some context about privacy and transformation behaviors. However, it lacks critical details such as whether this is a read-only or mutative operation, what permissions are required, how errors are handled, or what the output format looks like (especially since there's no output schema).

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, well-structured sentence that efficiently communicates the core purpose and key features without any wasted words. It front-loads the main action ('derive credentials') and follows with supporting details, making it easy to parse and understand quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of credential derivation with JSON-LD frames and proofs, the description is insufficient. There are no annotations to clarify safety or behavior, no output schema to describe results, and the description lacks details on error conditions, performance implications, or example use cases. For a tool with 3 parameters (including nested objects) and advanced cryptographic features, more context is needed for effective agent use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, with clear descriptions for 'originalCredential' as 'W3C Verifiable Credential', 'frame' as 'JSON-LD frame for selective disclosure', and 'nonce' as 'Nonce for derived proof'. The description adds value by explaining that these parameters are used for 'selective disclosure' and 'privacy-preserving presentations', providing context beyond the schema. However, it doesn't detail how the frame interacts with the credential or the role of the nonce in proofs.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb 'derive' and resource 'credentials', specifying the mechanism 'with selective disclosure using JSON-LD frames'. It distinguishes from siblings like 'issue_credential' or 'verify_credential' by focusing on derivation rather than creation or verification. However, it doesn't explicitly contrast with 'refresh_credential' or 'create_presentation_definition', which might have overlapping privacy-preserving aspects.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description mentions 'supports credential chaining and zero-knowledge proofs for privacy-preserving presentations', which implies usage for privacy-focused scenarios, but provides no explicit guidance on when to use this tool versus alternatives like 'create_presentation_definition' or 'submit_presentation'. There's no mention of prerequisites, exclusions, or specific contexts where this tool is preferred over siblings.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/AlyssonM/hiveauth-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server